为什么盒装原语不支持所有运算符?

Why boxed primitives doesn't support all operators?

观看 Effective Java 视频后,我注意到盒装基元类型仅支持六个比较运算符中的四个,即 <><=>= 并且不支持 ==!=.

我的问题是为什么盒装基元不支持所有运算符?

因为在 java 中,==!= 运算符总是通过引用比较对象,而装箱类型是对象。

他们确实支持 ==!=。他们只是没有按照您的期望去做。

对于引用,==!= 告诉您两个引用是否相等 - 即,它们是否引用同一个对象。

class Thingy {}
Thingy a = new Thingy();
Thingy b = new Thingy();
System.out.println(a == b); // prints false, because a and b refer to different objects

Thingy c = b;
System.out.println(b == c); // prints true, because b and c refer to the same object

这适用于所有 引用类型,包括盒装基元:

Integer a = new Integer(50);
Integer b = new Integer(50);
System.out.println(a == b); // prints false, because a and b refer to different objects

Integer c = b;
System.out.println(b == c); // prints true, because b and c refer to the same object

现在,引用不支持 <><=>=:

Thingy a = new Thingy();
Thingy b = new Thingy();
System.out.println(a < b); // compile error

然而,装箱的原语可以自动拆箱,并且拆箱的原语支持它们,所以编译器使用自动拆箱:

Integer a = new Integer(42);
Integer a = new Integer(43);

System.out.println(a < b);
// is automatically converted to
System.out.println(a.intValue() < b.intValue());

这种自动拆箱不会发生在 ==!= 中,因为这些运算符在没有自动拆箱的情况下已经有效 - 它们只是不符合您的预期。