Int,Long比较重使用equal替换==
生活随笔
收集整理的這篇文章主要介紹了
Int,Long比较重使用equal替换==
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先,==有很多限制,如Integer 類型的值在[-128,127] 期間,Integer 用 “==”是可以的(參考),超過范圍則不行,那么使用equal則代替則完全ok
public static void main(String[] args) {Long prop=4004L;Long prop1=4004l;Integer prop2=4004;Integer prop3=4004;if(prop2.equals(prop3)){System.out.println("hi");}else if(prop2==prop3){System.out.println("wrong");}if(prop1.equals(prop2.longValue())){System.out.println("helloworld");}else if(prop==prop1){System.out.println("you are wrong!");}返回結果
hi helloworld上面的示例說明使用"=="和equal還是有不小的區別的,equal可以替代==
Long源碼如下:
/*** Compares this object to the specified object. The result is* <code>true</code> if and only if the argument is not* <code>null</code> and is a <code>Long</code> object that* contains the same <code>long</code> value as this object.** @param obj the object to compare with.* @return <code>true</code> if the objects are the same;* <code>false</code> otherwise.*/public boolean equals(Object obj) {if (obj instanceof Long) {return value == ((Long)obj).longValue();}return false;}Integer源碼如下:
/*** Compares this object to the specified object. The result is* <code>true</code> if and only if the argument is not* <code>null</code> and is an <code>Integer</code> object that* contains the same <code>int</code> value as this object.** @param obj the object to compare with.* @return <code>true</code> if the objects are the same;* <code>false</code> otherwise.*/public boolean equals(Object obj) {if (obj instanceof Integer) {return value == ((Integer)obj).intValue();}return false;}?
轉載于:https://www.cnblogs.com/davidwang456/p/5870828.html
總結
以上是生活随笔為你收集整理的Int,Long比较重使用equal替换==的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Using Headless Mode
- 下一篇: Introduction to the