I was wondering if you can suggest something here.
I would like to have 2 methods:
doSomething(List<Data>) and
doSomething(List<Double>)
Since type of parameter is the same, Java is complaining
Is there a way to somehow make this overloading happen?
public void doSomething(List list) {
if(list.size() > 0) {
Object obj = list.get(0);
if(obj instanceof Data) {
doSomethingData((List<Data>)list);
} else if (obj instanceof Double) {
doSomethingDouble((List<Double>)list);
}
}
}
Sadly, no. Because Java implements generics via erasure those two methods would both compile down to:
doSomething(List)
Since you cannot have two methods with the same signature this will not compile.
The best you can do is:
doSomethingData(List<Data>)
doSomethingDouble(List<Double>)
or something equally nasty.
Why not just name them differently:
doSomethingDouble(List<Double> doubles);
doSomethingData(List<Data> data);
Generics are only available to the compiler, at compile time. They are not an execution time construct, as such the two methods above are identical, as at runtime both are equivalent too doSomething(List).
This doesn't work because of type erasure. One thing you could do is to add a dummy parameter, like so:
doSomething(List<Data>, Data)
doSomething(List<Double>, Double)
Ugly, but it works.
As an alternative, you could give the methods different names.