在 Java 中,为什么给定 2 个 varags 方法 foo(int...ints) 和 foo(Object...objects) 时,调用 foo() 没有歧义?

发布于 2024-07-23 08:33:34 字数 712 浏览 8 评论 0原文

如果我只声明 2 个 varargs 方法,如下所示:

public void foo(String... strings) {
    System.out.println("Foo with Strings");
}

然后

public void foo(int... ints) {
    System.out.println("Foo with ints");
}

有代码:

foo();

这是由于预期的歧义而导致的编译器错误。

但是,如果我只有以下 2 个版本的 foo:,

public void foo(Object... objects) {
    System.out.println("Foo with Objects");
}

然后

public void foo(int... ints) {
    System.out.println("Foo with ints");
}

代码

foo();

调用该方法的 ints 版本。 任何人都可以解释为什么第二个示例没有类似的歧义以及为什么它解析为 int 方法而不是 Object 方法。 谢谢。

If I declare just the 2 varargs methods as follows:

public void foo(String... strings) {
    System.out.println("Foo with Strings");
}

and

public void foo(int... ints) {
    System.out.println("Foo with ints");
}

and then have the code:

foo();

this is a compiler error due to the ambiguity as expected.

However if I have just the following 2 versions of foo:

public void foo(Object... objects) {
    System.out.println("Foo with Objects");
}

and

public void foo(int... ints) {
    System.out.println("Foo with ints");
}

then the code

foo();

calls the ints version of the method. Can anyone explain why the second example isn't similarly ambiguous and why it resolves to the int method over the Object method. Thanks.

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

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

发布评论

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

评论(2

我纯我任性 2024-07-30 08:33:34

如果我在准备 scjp 时记得正确的话,在第一种情况下,您有 2 个参数,它们之间没有关系,因此编译器无法选择一个。

在第二种情况下,启用装箱(1.5+)后,int 可以是 Integer,它是 Object 的子集,并且编译器在发生冲突时将始终使用最具体的定义。 所以优先考虑整数(int)。

If I recall properly from when I was preparing the scjp, in the first case you have 2 arguments with no relation between them, so the compiler can't choose one.

In the second, with boxing enabled (1.5+), int can be Integer which is a subset of Object, and the compiler, in case of conflict, will always use the most specific definition. So Integer (int) is prioritized.

Bonjour°[大白 2024-07-30 08:33:34

Java 将始终使用尽可能接近的类型,因此当您将 int 传递到方法中时,如果您没有 int... 方法,它会自动将它们装箱为 Integers 并使用 Object.... 因为有一个 int。 .. 方法,Java 将首先使用该方法。 这是Java编译器设计中的一个选择。

Java will always use the closest type possible, so when you pass ints into the method, if you didn't have the int... method, it would autobox them into Integers and use Object.... Since there is an int... method, Java will use that first. This is a choice in the Java compiler design.

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