Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the correct type of list?

If I have a method like this (for simplicity assume integers):

public static List<Integer> doSomething(List<Integer> list) {
   // logic here  
}

and I need for my processing to create internally a new list which I will create and somehow populate and return to the caller, how can I do it since I don't know what type of list the caller passed in?

I don't want to return a List of different type that what the caller passed in.

E.g. If the caller passed a LinkedList and I don't want to return an ArrayList.

How can this issue best be approached?

like image 830
Cratylus Avatar asked Dec 17 '22 04:12

Cratylus


1 Answers

You shouldn't tie your implementation to a particular implementation of List, the idea of using an interface is that, from the outside, it shouldn't matter what concrete class you're instantiating as long as it conforms to the List interface.

EDIT :

Anyway, here's a possible way:

List<Integer> lst1 = new ArrayList<Integer>();
Class<?> klass1 = lst1.getClass();
List<Integer> copy1 = (List<Integer>) klass1.newInstance();
System.out.println(copy1.getClass().getName());
> java.util.ArrayList

List<Integer> lst2 = new LinkedList<Integer>();
Class<?> klass2 = lst2.getClass();
List<Integer> copy2 = (List<Integer>) klass2.newInstance();
System.out.println(copy2.getClass().getName());
> java.util.LinkedList

As you can see in the console, the copies are instances of the same class as the original list.

like image 164
Óscar López Avatar answered Jan 01 '23 07:01

Óscar López