在 Java 中,为什么给定 2 个可变参数方法 foo(int... ints) 和 foo(Object... objects) 调用 foo() 没有歧义? [英] In Java, why is the call foo() not ambigious given 2 varags methods foo(int... ints) and foo(Object... objects)?

查看:29
本文介绍了在 Java 中,为什么给定 2 个可变参数方法 foo(int... ints) 和 foo(Object... objects) 调用 foo() 没有歧义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只声明 2 个可变参数方法如下:

If I declare just the 2 varargs methods as follows:

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

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

然后有代码:

foo();

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

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

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

However if I have just the following 2 versions of 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 版本.任何人都可以解释为什么第二个例子没有类似的歧义,以及为什么它通过 Object 方法解析为 int 方法.谢谢.

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.

推荐答案

如果我记得我在准备 scjp 的时候没记错的话,在第一种情况下你有 2 个参数,它们之间没有关系,所以编译器不能选择一个.

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.

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

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.

这篇关于在 Java 中,为什么给定 2 个可变参数方法 foo(int... ints) 和 foo(Object... objects) 调用 foo() 没有歧义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆