开发者

Convert Collection to List [duplicate]

开发者 https://www.devze.com 2022-12-24 10:41 出处:网络
This question already has answers here: How to convert a Collection to List? (11 answers) Closed 7 years ago.
This question already has answers here: How to convert a Collection to List? (11 answers) Closed 7 years ago.

I would like to ask: how do you convert a Collection to a 开发者_如何转开发List in Java?


Collection<MyObjectType> myCollection = ...;
List<MyObjectType> list = new ArrayList<MyObjectType>(myCollection);

See the Collections trail in the Java tutorials.


If you have already created an instance of your List subtype (e.g., ArrayList, LinkedList), you could use the addAll method.

e.g.,

l.addAll(myCollection)

Many list subtypes can also take the source collection in their constructor.


List list;
if (collection instanceof List)
{
  list = (List)collection;
}
else
{
  list = new ArrayList(collection);
 }


Make a new list, and call addAll with the Collection.


Thanks for Sandeep putting it- Just added a null check to avoid NullPointerException in else statement.

if(collection==null){
  return Collections.emptyList();
}
List list;
if (collection instanceof List){
  list = (List)collection;
}else{
  list = new ArrayList(collection);
}


you can use either of the 2 solutions .. but think about whether it is necessary to clone your collections, since both the collections will contain the same object references


Collection and List are interfaces. You can take any Implementation of the List interface: ArrayList LinkedList and just cast it back to a Collection because it is at the Top

Example below shows casting from ArrayList

public static void main (String args[]) {
    Collection c = getCollection();
    List myList = (ArrayList) c;
}

public static Collection getCollection()
{
    Collection c = new ArrayList();
    c.add("Apple");
    c.add("Oranges");
    return c;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号