Method overloading

2019-06-28 03:50发布

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?

5条回答
疯言疯语
2楼-- · 2019-06-28 04:26
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);
        }
    }
}
查看更多
时光不老,我们不散
3楼-- · 2019-06-28 04:28

Why not just name them differently:

doSomethingDouble(List<Double> doubles);
doSomethingData(List<Data> data);
查看更多
4楼-- · 2019-06-28 04:32

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.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-06-28 04:36

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.

查看更多
放我归山
6楼-- · 2019-06-28 04:46

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

查看更多
登录 后发表回答