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?
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:
method1(int a, int b)method1(Integer... a)In your case, the first point applies and
method1(int, int)is called.(To be more precise, your method uses varags and has a lower priority than a simple boxing conversion. In other words, if there were a
method1(Integer a, Integer b)it would come beforemethod1(Integer... a)in the hierarchy)Why is it so? A comment in 15.12.2 give a hint: