简体   繁体   English

重载varargs方法时的怪异行为

[英]Weird behaviour when overloading varargs method

Usually methods with a fixed number of arguments are preferred over overloaded methods with a variable number of arguments. 通常,带有固定数量参数的方法比带有可变数量参数的重载方法更可取。 However, this example behaves differently: 但是,此示例的行为有所不同:

public class Main{
 public static void main(String[] args){
  print(1);
  print(1,2);
  print(new String[]{"a","b"});
  print(new String[][]{{"a","b"},{"c","d"}});
 }

 public static void print(Object object){
  System.out.println("single argument method");
  System.out.println(object);
 }

 public static void print(Object object0,Object object1){
  System.out.println("two argument method");
  System.out.println(object0);
  System.out.println(object1);
 }

 public static void print(Object... objects){
  System.out.println("varargs method with "+objects.length+" arguments");
  for(Object object : objects){
   System.out.println(object);
  }
 }
}

Output: 输出:

single argument method
1
two argument method
1
2
varargs method with 2 arguments
a
b
varargs method with 2 arguments
[Ljava.lang.String;@5e2de80c
[Ljava.lang.String;@1d44bcfa

The third line of main calls the method with one argument, which is a String[] with two elements. main的第三行使用一个参数调用该方法,该参数是带有两个元素的String []。 But that doesn't execute the method with one argument, but instead executes the varargs method and acts like I gave it two arguments (which is sort of normal, since it's an array). 但这并没有使用一个参数执行该方法,而是执行了varargs方法并像我给它提供了两个参数一样进行操作(这是正常的,因为它是一个数组)。

Now the question: Should this happen? 现在的问题是: 这会发生吗? Have I found a bug or undocumented behaviour? 我是否发现了错误或未记录的行为? Is there a reason why it does this? 有这样做的理由吗?

Why I'm doing this: I want to make a shortcut for printing to console which can both take in an arbitrary number of arguments (for multiple lines) and also print arrays and lists in a nice way. 为什么这样做:我想为打印到控制台提供一个快捷方式,它既可以接受任意数量的参数(用于多行),也可以以一种很好的方式打印数组和列表。

Should this happen? 这应该发生吗?

Yes

Have I found a bug or undocumented behaviour? 我是否发现了错误或未记录的行为?

No 没有

Is there a reason why it does this? 有这样做的理由吗?

Yes. 是。 From Oracle : 从Oracle

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process . 确实必须在数组中传递多个参数, 但是varargs功能自动执行并隐藏了进程 Furthermore, it is upward compatible with preexisting APIs. 此外,它与先前存在的API 向上兼容

When you use an array explicitly it still matches the varargs signature. 显式使用数组时,它仍与varargs签名匹配。 It was done so so that people could easily switch an array parameter to varargs without breaking existing integration points. 这样做是为了使人们可以轻松地将数组参数切换为varargs,而不会破坏现有的集成点。

It's exactly the same reason that main can be String[] or String... 这与main可以是String[]String...原因完全相同String...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM