叫哪种方法? (整数... a)vs.(int a,int b) [英] Which method is called? (Integer... a) vs. (int a, int b)

查看:132
本文介绍了叫哪种方法? (整数... a)vs.(int a,int b)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现了一个非常有趣的Java技巧:

I just found out about a very interesting Java trick:

void method1(Integer... a){
}

因此,您可以根据需要为此方法提供尽可能多的整数。

So you can give this method as many integers as you want.

现在如果我有类似的(重载)方法:

Now if I have a similar (overloaded) method like this:

void method1(int a, int b){

}

当我运行时,哪种方法运行执行以下行:

Which method runs when I execute the following line:

method1(1, 2);

好吧,我可以通过使用不同的方法指令测试它而非常容易找到它但是当我考虑重载方法中的规则然后我必须确保每个重载方法必须相同,以便编译器确切知道要使用哪个。

Well, I could find that out very easily by just testing it out with different method instructions but when I think about the "rules" in "overloading" methods then I have to make sure that every overloaded method must be identical so that the compiler knows exactly which one to use.

在我看来,上面的代码不应该工作,因为编译器应该混淆。但是,当我尝试它时,它有效。

In my opinion, the code above shouldn't work because the compiler should be confused. But when I try it out it works.

那么..有没有人知道更多关于此的背景信息?

So.. does anyone know a bit more background information about this?

推荐答案

要确定应该调用哪个方法,编译器将按照以下列表进行操作,详见 JLS#5.3 JLS#15.12.2

To determine which method should be called, the compiler goes through the following list, as detailed in the JLS #5.3 and JLS #15.12.2:


  • 身份转换(第5.1.1节) => method1(int a,int b)

  • 扩大原始转换(§5.1.2)

  • 扩大参考转换(§5.1.5)

  • a拳击转换(§5.1.7)可选地后跟加宽引用转换 ==> method1(整数... a)

  • 一个拆箱转换(第5.1.8节),可选地后跟一个加宽的基元转换。

  • an identity conversion (§5.1.1) => method1(int a, int b)
  • a widening primitive conversion (§5.1.2)
  • a widening reference conversion (§5.1.5)
  • a boxing conversion (§5.1.7) optionally followed by widening reference conversion ==> method1(Integer... a)
  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

在你的情况下,第一点适用,并且调用 method1(int,int)

In your case, the first point applies and method1(int, int) is called.

(更准确地说,您的方法使用varags并且优先级低于简单的装箱转换。换句话说,如果有一个方法1(整数a,整数b)它将出现在 method1(整数... a)

为什么会这样? 15.12.2中的注释给出了一个提示:

Why is it so? A comment in 15.12.2 give a hint:


这保证了在Java SE 5.0之前在Java编程语言中有效的任何调用都是因为引入变量arity方法,隐式装箱和/或拆箱而不被认为是模棱两可的。

This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing.

这篇关于叫哪种方法? (整数... a)vs.(int a,int b)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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