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

Java 为什么装箱原语不支持所有运算符?,java,autoboxing,Java,Autoboxing,在观看了有效的Java视频后,我注意到装箱原语类型只支持六个比较运算符中的四个,它们分别为、=和不支持==和!= 我的问题是为什么装箱原语不支持所有运算符?因为在java中==和!=操作符总是通过引用来比较对象,而装箱类型就是对象。它们支持==和!=。他们只是没有做到你所期望的 对于引用,==和!=告诉您两个引用是否相等,即它们是否引用同一对象 class Thingy {} Thingy a = new Thingy(); Thingy b = new Thingy(); System.out

在观看了有效的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
现在,引用不支持or=:

但是,装箱的原语可以自动取消装箱,并且取消装箱的原语确实支持它们,因此编译器使用自动取消装箱:

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());

如果==或!=,则不会自动取消装箱,因为这些操作符在没有自动取消装箱的情况下已经是有效的-它们只是没有达到您所期望的效果。

Boxed primitives==普通对象,它们不再是原语。
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());