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