How to declare a variable according to an unknown List type of the input variable in Java?
For example::
You are given arr1, you need to (shallow) copy from arr1 to arr2. But you don't know what type of list arr1 is.
This is the code that I use, if I want to declare arr2, I have to go through all possible cases of types of List.
static List<Object> funcOri(List<Object> arr1, List<Object> arr2) {
if (arr1 instanceof ArrayList<?>) {
arr2 = new ArrayList<Object>(arr1);
} else if (arr1 instanceof LinkedList<?>) {
arr2 = new LinkedList<Object>(arr1);
} else if (...) {
;
}
return arr2;
}
Is there a simpler way to declare arr2 according to the type of arr1 is?
Maybe something that simply looks like::
static List<Object> funcWanted(List<Object> arr1, List<Object> arr2) {
arr2 = new XXXList<Object>(arr1); // where XXXList is base on the type of list the arr1 is
return arr2;
}
Unless I am completely misunderstanding your problem, this is what you need (Java 8)
If you were to change
originalList type toList<Integer>orLinkedList<String>, thefuncOriwill work the same.