Method overloading

心不动则不痛 提交于 2019-12-10 16:24:05

问题


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.



来源:https://stackoverflow.com/questions/4500790/method-overloading

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!