Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method accepts List<String>, needs to return same implementation of List<String>

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.

like image 979
Bryan Avatar asked Jan 25 '26 13:01

Bryan


1 Answers

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:

  1. Implementation may have not accessible constructor
  2. There may be no no-args constructors
  3. You will have to introspect all issues by yourself
  4. Many more possible troubles with that that I am not aware of

In general, don't do that. Don't stick to implementation.

like image 88
Antoniossss Avatar answered Jan 27 '26 02:01

Antoniossss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!