class="java" name="code">
Long originalLong = (long) -128;
Long newLong = (long) -128;
System.out.println("Object Compare:" + (originalLong == newLong));
System.out.println("LongValue Compare:" + (originalLong.longValue() == newLong.longValue()));
System.out.println("Equals Compare:" + originalLong.equals(newLong));
结果为:
Object Compare:true
LongValue Compare:true
Equals Compare:true
Long originalLong = (long) 127;
Long newLong = (long) 127;
System.out.println("Object Compare:" + (originalLong == newLong));
System.out.println("LongValue Compare:" + (originalLong.longValue() == newLong.longValue()));
System.out.println("Equals Compare:" + originalLong.equals(newLong));
结果为:
Object Compare:true
LongValue Compare:true
Equals Compare:true
Long originalLong = (long) -129;
Long newLong = (long) -129;
System.out.println("Object Compare:" + (originalLong == newLong));
System.out.println("LongValue Compare:" + (originalLong.longValue() == newLong.longValue()));
System.out.println("Equals Compare:" + originalLong.equals(newLong));
结果为:
Object Compare:false
LongValue Compare:true
Equals Compare:true
Long originalLong = (long) 128;
Long newLong = (long) 128;
System.out.println("Object Compare:" + (originalLong == newLong));
System.out.println("LongValue Compare:" + (originalLong.longValue() == newLong.longValue()));
System.out.println("Equals Compare:" + originalLong.equals(newLong));
结果为:
Object Compare:false
LongValue Compare:true
Equals Compare:true
总结:当Long对象的值在long类型的区间内是,比较对象的值是否相等可以两个对象直接用“==”比较,否则需要利用其他两种方式比较,才能得到正确的结果。
结论:比较两个Long对象昂的值是否相等的时候,直接使用其他两种方式比较,而不要使用“==”
caozuofu.html" target="_blank">操作符。