Sebastian Mendez
Sebastian Mendez

Reputation: 2971

Return same implementation of List as passed in parameter

Let's say I have a function similar to the following:

public static List<Integer> empty(List<Integer> list) {
    List<Integer> empty = new ArrayList<>();
    return empty;
}

which I want to return a List of the same implementation as the passed in list. For my example function, this is only true if the passed in list is an ArrayList. How do I initialize a List based on the implemenation of list (e.g. so the returned List would be a LinkedList if list was a LinkedList)?

Upvotes: 0

Views: 92

Answers (1)

Amit Bera
Amit Bera

Reputation: 7315

Not sure why you need this. For me, it is a bad design. However, you can do it using reflection:

public static List<Integer> empty(List<Integer> list) throws InstantiationException, IllegalAccessException {
    Class<? extends List> c = list.getClass();
    return c.newInstance();
}

Note: above example only works if List implementation class have a public accessible empty constructor else you will get an exception.

Upvotes: 4

Related Questions