crumbs357
crumbs357

Reputation: 25

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

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).

Upvotes: 2

Views: 2571

Answers (3)

TakinosaJi
TakinosaJi

Reputation: 408

Here it is:

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

Upvotes: -1

MeBigFatGuy
MeBigFatGuy

Reputation: 28568

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);

Upvotes: 2

andersoj
andersoj

Reputation: 22874

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.

Upvotes: 1

Related Questions