使用Java中的Integer对象比较运算符的安全性

use*_*107 0 java integer reference comparison-operators

什么时候使用比较运算符是安全的,例如==,> =,<在Java中使用Integer对象而不是原始的int?

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

我知道==对于引用是危险的,你应该使用.equals,但其他运算符呢?例如

int x = 7;
int y = 7;
Integer a = new Integer(7);
Integer b = new Integer(7);

System.out.println(x == y);
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a <= b);
Run Code Online (Sandbox Code Playgroud)

版画

true
false // Why you should use .equals
true
true // Seemed dangerous but it worked?
Run Code Online (Sandbox Code Playgroud)

是否可以使用除double equals以外的任何东西(So>,<,> =和<=是安全吗?),还是应该使用.compareTo()方法?

Sot*_*lis 5

变量引用时很危险null.取消装箱操作将导致NullPointerException.

<=>=运营商比不同==.它们只能应用于数字基元类型(和值),因此引用相等性不是问题.