I’m giving my first steps with generics, and I’ve just coded a generic function to compare two List objects, like this
public static <T> List<T> diffAdded(List<T> source, List<T> dest) {
List<T> ret = new ArrayList<T>();
for(T element: dest) {
if (!source.contains(element)) {
ret.add(element);
}
}
return ret;
}
Everything works fine, but I’m instantiating an ArrayList, because obviously I cannot instantiate an interface List
the fact is that I want to return an object of the same type as source…
how do you handle these kind of situations?
can I face any cast trouble with the method as it is right now?
thanks a lot
The answer to this question is almost always that “returning an object of the same type as the source” is not actually relevant to your application, and that you’re going about things the wrong way.
If your caller needs a specific
Listimplementation, because they’ll be doing a specific kind of operation on it, then they can do the copying themselves…but if your method takes an arbitrary argument of typeList, and the output changes semantically depending on the exact implementation of the input, then that’s a huge code smell.Leave your code as it is, and if your method’s callers really, really need a specific implementation, then they can copy your output into that implementation themselves.