0

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

Sebastian Mendez
  • 2,859
  • 14
  • 25
  • Why would you want to? – daniu Sep 09 '19 at 17:03
  • In general, you can't do this. The type of `list` may not be accessible or have an accessible constructor (although you could change it using reflection, provided there isn't a security manager that will block you). Or the only constructor(s) may require arguments that your code is unable to supply. `list` may even be something weird like an instance of a private inner class of an abstract containing class, bound to an instance of the containing class. – Ted Hopp Sep 09 '19 at 18:40
  • I was just curious if this was possible. – Sebastian Mendez Sep 09 '19 at 23:34

1 Answers1

4

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.

Amit Bera
  • 7,075
  • 1
  • 19
  • 42