在使用Integer对象而不是原始int的情况下,何时在Java中使用比较运算符(例如==,> =,<)安全吗?
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);
印刷
true
false // Why you should use .equals
true
true // Seemed dangerous but it worked?
是否可以使用除double equals之外的其他任何方法(因此>,<,> =和<=是安全的?),还是应该使用.compareTo()方法?
变量引用很危险null
。取消装箱操作将导致NullPointerException
。
在<=
与>=
运营商比不同==
。它们只能应用于数字基本类型(和值),因此引用相等性不是问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句