开发者

Method overloading

开发者 https://www.devze.com 2023-01-31 10:35 出处:网络
I was wondering if you can suggest something here. I would li开发者_高级运维ke to have 2 methods:

I was wondering if you can suggest something here.

I would li开发者_高级运维ke 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?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消