方法重载

发布于 2024-10-08 19:06:12 字数 187 浏览 0 评论 0原文

我想知道你是否可以在这里提出一些建议。

我想要两种方法:

doSomething(List<Data>) and
doSomething(List<Double>)

由于参数类型相同,Java 抱怨

有没有办法以某种方式使这种重载发生?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

月依秋水 2024-10-15 19:06:12

遗憾的是,没有。因为 Java 通过擦除来实现泛型,所以这两个方法都将编译为:

doSomething(List)

由于不能有两个具有相同签名的方法,因此将无法编译。

你能做的最好的事情就是:

doSomethingData(List<Data>)
doSomethingDouble(List<Double>)

或者做同样令人讨厌的事情。

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.

手长情犹 2024-10-15 19:06:12
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);
        }
    }
}
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);
        }
    }
}
你与昨日 2024-10-15 19:06:12

为什么不只是以不同的方式命名它们:

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

Why not just name them differently:

doSomethingDouble(List<Double> doubles);
doSomethingData(List<Data> data);
不必了 2024-10-15 19:06:12

泛型仅在编译时可供编译器使用。它们不是执行时构造,因此上面的两个方法是相同的,因为在运行时两者也是等效的doSomething(List)

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

离线来电— 2024-10-15 19:06:12

由于类型擦除,这不起作用。您可以做的一件事是添加一个虚拟参数,如下所示:

doSomething(List<Data>, Data)
doSomething(List<Double>, Double)

丑陋,但它有效。

作为替代方案,您可以为这些方法指定不同的名称。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文