Search code examples
javaclassinterface-implementation

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


Solution

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