I have a method that needs to accept any implementation of List, create a newList of the same implementation, and return the newList. I'm trying to figure out how to ensure that newList is of the same implementation of List as input. See the attached code:
static List<String> get(List<String> input){
// do some stuff
List<String> newList = new (?????);
// do some stuff with newList
return newList;
}
I can overload the method for ArrayList, LinkedList, Vector, etc. but I want to see if it can this be done without repeating a bunch of code.
You can try something like this
static List<String> get(List<String> input){
// do some stuff
List<String> newList = (List<String>)input.getClass().newInstance();
// do some stuff with newList
return newList;
}
input.getClass() will return actual runtime implementation type.
But this may not always work:
In general, don't do that. Don't stick to implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With