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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM