Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 228
user236691 Avatar asked Dec 28 '09 05:12

user236691


People also ask

Can we convert collection to List in Java?

Use addAll to Convert Collection Into List in Java. addAll() is a method provided in the collections framework that we can use to convert a collection to a list. The elements from the collection can be specified one by one or as an array.

How do you convert from one collection to another in Java?

Thanks to the Collection framework in Java, copying collections from one to another is extremely easy. Since every Collection class implements a Collection interface that defines the addAll() method, which can be used to create a collection from contents of another collection.


2 Answers

As other people have mentioned, ArrayList has a constructor that takes a collection of items, and adds all of them. Here's the documentation:

http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29

So you need to do:

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

However, in another comment you said that was giving you a compiler error. It looks like your class MyGraph is a generic class. And so getVertices() actually returns type V, not type myNode.

I think your code should look like this:

public V getNode(int nodeId){         ArrayList<V> myNodeList = new ArrayList<V>(this.getVertices());         return myNodeList(nodeId); } 

But, that said it's a very inefficient way to extract a node. What you might want to do is store the nodes in a binary tree, then when you get a request for the nth node, you do a binary search.

like image 72
Chad Okere Avatar answered Sep 20 '22 03:09

Chad Okere


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 ); 
like image 38
Ashish Dwivedi Avatar answered Sep 23 '22 03:09

Ashish Dwivedi