Why does autoboxing happen in the method
public static int compareAges(Person p1, Person p2) {
return ((Integer) p1.getAge()).compareTo(p2.getAge());
}
but we get a compiler error in the method
public static int compareAges(Person p1, Person p2) {
return p1.getAge().compareTo(p2.getAge());
}
?
As per the Javadocs:
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
So, in other words, why is the compiler not able to perform autoboxing in the second method? Is it because in the second method, the binding is not explicit, whereas the binding is unambiguous in the first method.
Java chose not to support Autoboxing when you call a method on a primitive probably because James Gosling would never do such a thing himself so this of course means that no other developer will ever need it.
If you don't get the reference check this answer.
Because James Gosling said so:
I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++.
James Gosling. Source: http://www.gotw.ca/publications/c_family_interview.htm