[java] Java - How to convert type collection into ArrayList?

public class MyGraph<V,E> extends SparseMultigraph<V,E>{
    private ArrayList<MyNode> myNodeList;

    public MyNode getNode(int nodeId){
        myNodeList = new ArrayList<MyNode>();
        myNodeList = (ArrayList<MyNode>)this.getVertices();
        int i;

The following are the error msg:

Exception in thread "main" java.lang.ClassCastException: java.util.Collections$UnmodifiableCollection cannot be cast to java.util.ArrayList...

Can anyone help?

This question is related to java collections

The answer is


More information needed for a definitive answer, but this code

myNodeList = (ArrayList<MyNode>)this.getVertices();

will only work if this.getVertices() returns a (subtype of) List<MyNode>. If it is a different collection (like your Exception seems to indicate), you want to use

new ArrayList<MyNode>(this.getVertices())

This will work as long as a Collection type is returned by getVertices.


Try this code

Convert ArrayList to Collection

  ArrayList<User> usersArrayList = new ArrayList<User>();

  Collection<User> userCollection = new HashSet<User>(usersArrayList);

Convert Collection to ArrayList

  Collection<User> userCollection = new HashSet<User>(usersArrayList);

  List<User> userList = new ArrayList<User>(userCollection );

The following code will fail:

List<String> will_fail =  (List<String>)Collections.unmodifiableCollection(new ArrayList<String>());

This instead will work:

List<String> will_work = new ArrayList<String>(Collections.unmodifiableCollection(new ArrayList<String>()));

public <E> List<E> collectionToList(Collection<E> collection)
{
    return (collection instanceof List) ? (List<E>) collection : new ArrayList<E>(collection);
}

Use the above method for converting the collection to list