自动装箱规则

Autoboxing rules

为什么方法中会自动装箱

public static int compareAges(Person p1, Person p2) {
    return ((Integer) p1.getAge()).compareTo(p2.getAge());
}

但是我们在方法中遇到编译器错误

public static int compareAges(Person p1, Person p2) {
    return p1.getAge().compareTo(p2.getAge());
}

?


根据 Javadocs:

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

那么,换句话说,为什么编译器无法在第二种方法中执行自动装箱?是不是因为在第二种方法中,绑定不是显式的,而在第一种方法中绑定是明确的。

JavaDoc 中关于自动装箱的内容https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.

  • Assigned to a variable of the corresponding wrapper class.

第二种方法不会自动装箱。

Java 当你在基元上调用方法时选择不支持自动装箱可能是因为 James Gosling 自己永远不会做这样的事情,所以这当然意味着没有其他开发人员需要它。

如果您没有得到参考检查 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