Java pit encountered: Comparison of Long type

 
 
public static void main(String[] args) {
Long goodsId=127L;
Long itemId=127L;
//true
System.out.println(goodsId == itemId);
goodsId=128L;
itemId=128L;
//false
System.out.println(goodsId == itemId);
Long x=new Long(127);
Long y=new Long(127);
//false
System.out.println(x == y);
//true
System.out.println(x.equals(y));
}
 

Long is a reference type, to compare the size of two Long, must use equals rather than using ==

However, when the Long and the constant value is a constant less than one byte, two Long a constant point to the same content;

Long and constant when constant value greater than one byte, two different constants Long directed content.

Concluded, without reference to the comparison must use equals use ==

Guess you like

Origin www.cnblogs.com/lizixiang/p/11225514.html