Method overloading

2019-06-28 04:01发布

问题:

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?

回答1:

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);
        }
    }
}


回答2:

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.



回答3:

Why not just name them differently:

doSomethingDouble(List<Double> doubles);
doSomethingData(List<Data> data);


回答4:

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).



回答5:

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.