开发者

How to create a new list of same type as old list in Java?

开发者 https://www.devze.com 2023-02-13 12:19 出处:网络
I\'m trying to write a method that takes in a List and create a new List of the same type based on it. That is, if the input list is an ArrayList, then I want the method to create a new ArrayList. The

I'm trying to write a method that takes in a List and create a new List of the same type based on it. That is, if the input list is an ArrayList, then I want the method to create a new ArrayList. The problem is that the program won't know if the List is an ArrayList or a LinkedList until runtime.

So far I've tried using开发者_开发技巧 the clone() method, but I don't think it works because the List class doesn't have clone() defined, and when I cast the input list as an Object and then clone then recast as a List, it also doesn't work (I'm not sure why).


All the standard lists from the JDK support clone, so

List copy = (List)((Cloneable)somelist).clone()

should work fine.

of course you can use reflection

Class c = somelist.getClass();
List newlist = (List)c.newInstance();
newlist.addAll(somelist);


Can you say more about why you want to do this? Without a good rationale, I'd contend:

Consider not doing this at all, but instead:

static <T> List<T> cloneMyList(final List<T> source)
{
  return new ArrayList<T>(source);
} 

If what you REALLY want is an efficient way to create a second copy of a known list, maybe the underlying implementation type really doesn't matter. In that case, just use an ArrayList which can be efficiently allocated using the List copy constructor.


Here it is:

List<YourType> destinationList = new ArrayList<>(sourceList.size());
Collections.copy(destinationList, sourceList);
0

精彩评论

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

关注公众号