How do I write a static method in Java that will take a List, perform an action on each element, and return the result (without affecting the original of course)?
For example, if I want to add 2 to each element what goes in the … here? The concrete return type must be the same, e.g. if my List is a LinkedList with values 1,2,3 I should get back a LinkedList with values 3,4,5. Similarly for ArrayList, Vector, Stack etc, which are all Lists.
I can see how to do this using multiple if (lst instanceof LinkedList) ... etc… any better way?
import java.util.List;
public class ListAdd {
static List<Integer> add2 (List<Integer> lst) {
...
return result;
}
}
OK well someone mentioned reflection. It seems to be an elegant solution:
Concise, but it thows an checked exception, which is not nice.
Also, wouldn’t it be nicer if we could use the method on concrete types as well, e.g. if
ais anArrayListwith values 1, 2, 3, we could calladd2(a)and get anArrayListback? So in an improved version, we could make the signature generic:I think throwing a runtime exception is the least worst option if a list without a nullary construcor is passed in. I don’t see a way to ensure that it does. (Java 8 type annotations to the rescue maybe?) Returning
nullwould be kind of useless.The downside of using this signature is that we can’t return an
ArrayListetc as the default, as we could have done as an alternative to throwing an exception, since the return type is guaranteed to be the same type as that passed in. However, if the user actually wants an ArrayList (or some other default type) back, he can make an ArrayList copy and use the method on that.If anyone with API design experience reads this, I would be interested to know your thoughts on which is the preferable option: 1) returning a List that needs to be explicity cast back into the original type, but enabling a return of a different concrete type, or 2) ensuring the return type is the same (using generics), but risking exceptions if (for example) a singleton object without a nullary constructor is passed in?