跳到主要內容

[Java] equals 與 ==

今天被同事問到Java equals的問題,發現觀念已經有點模糊了…老啦

只記得數字就用==,字串就用equals,至於原因已經還給老師了

Sample:

一開始真的有點打結,不同的物件怎麼會有相同的hashCode…是我的記憶有了錯誤嗎XD

想不通只好各種解釋…

String s1 = new String("ABC");
String s2 = new String("ABC");
System.out.println("s1." + s1 + ".hashCode:" + s1.hashCode());
System.out.println("s2." + s2 + ".hashCode:" + s2.hashCode());

if(s1.equals(s2)){
 System.out.println("s1 is equals s2 !");
}else{
 System.out.println("s1 is not equals s2 !");
}

if(s1 == s2){
 System.out.println("s1 = s2 !");
}else{
 System.out.println("s1 != s2 !");
}

Object o1 = new Object();
Object o2 = new Object();
System.out.println("o1." + o1 + ".hashCode:" + o1.hashCode());
System.out.println("o2." + o2 + ".hashCode:" + o2.hashCode());

if(o1.equals(o2)){
 System.out.println("o1 is equals o2 !");
}else{
 System.out.println("o1 is not equals o2 !");
}

if(o1 == o2){
 System.out.println("o1 = o2 !");
}else{
 System.out.println("o1 != o2 !");
}

Console log:

s1.ABC.hashCode:64578
s2.ABC.hashCode:64578
s1 is equals s2 !
s1 != s2 !
o1.java.lang.Object@7852e922.hashCode:2018699554
o2.java.lang.Object@4e25154f.hashCode:1311053135
o1 is not equals o2 !
o1 != o2 !

後來才想到可以看一下Source Code

原來String有去覆寫hashCode()及equals()

hashCode()改成只要相同valeu就會得到相同的hashCode

equals()也是改成比較value是否相同

而原Object的hashCode()應該是每個不同的物件都會有不同的hashCode

原Object的equals()則是直接回傳==的結果~

String source code:

private int hash; // Default to 0

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

留言

這個網誌中的熱門文章

[Swift] String Format for NT$

  var amount = NSNumber(int: 8880) var _currencyFormatter = NSNumberFormatter() _currencyFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle //_currencyFormatter.currencyCode = "NT$ " //_currencyFormatter.formatterBehavior = NSNumberFormatterBehavior.BehaviorDefault //_currencyFormatter.negativeFormat = "-$#,##0" _currencyFormatter.positiveFormat = "NT$ #,##0" _currencyFormatter.stringFromNumber(amount)   輸出結果︰ NT$ 8,880   參考︰ http://www.cokco.cn/thread-35548-1-1.html http://www.freair.com/bbs/simple/?t558.html

小米路由器 mini 刷機

這次會來刷機是因為要給 MOD 使用 但原本的 小米路由器 mini 沒支援 IPTV 不想再買一台路由器(已經有四台了XD,有3台是被淘汰的)   參考文章︰ 1.  ERIC的攝影世界 - 小米路由器mini 免USB打開SSH  ( 備份檔案 ) 2.  ERIC的攝影世界 - 小米路由器mini韌體刷openwrt PandoraBox韌體  ( 備份檔案 ) 3.  寫寫東西 分享心得 - 小米路由器mini 改韌體 可看中華電信MOD iptv功能開啟 刷機 刷rom 直通MOD 老毛子Padavan固件 華碩 RT-AC54U  ( 備份檔案 )   其實找了很多篇文章,大部份都教用官方的那招,但不知道為什麼我就是取不到SSH的密碼 https://d.miwifi.com/rom/ssh  這個一直導不到要的那頁… 所以後來是用了  ERIC的攝影世界 - 小米路由器mini 免USB打開SSH  的第二招  免USB打開SSH 步驟︰ 1. 手動更新韌體到小米路由器mini 穩定版 2.8.14 ( 備用檔案 ) 2. 然後按  ERIC的攝影世界 - 小米路由器mini 免USB打開SSH  的 1.2.3.4.5   2.1 登入  小米路由器mini控制台  後複制網址     http://192.168.31.1/cgi-bin/luci/;stok=521b849e00a11c5b6743aa275ba84ed8 /web/home#router   2.2 將下面的網址紅色部份換成自己的,然後再貼到Browser上     http://192.168.31.1/cgi-bin/luci/;stok=521b849e00a11c5b6743aa275ba84ed8 /api/xqsystem/set_name_password?oldPwd=路由器控制台管理密碼&newPwd=admin     順利的會得到  {"code":0}   2.3 將下面的網址紅色部份換成自己的,然後再貼到Browser上     http://192.168.31.1/cgi-bin/luci/;stok=521b849e00a11c5b6743aa275ba84ed8 /api/x

[PS4 VR] 影片轉檔

怎麼用索尼PSVR看安卓VR 360° 3D視頻 => 將雙眼視頻改成單眼視頻,將格式改成MPEG-4,解析度1920*1080 ,60幀 15000kbps https://kknews.cc/tech/vme9a5l.html ============================================================== Wondershare Filmora:  8.0.0 for Mac 破解版下載 http://www.iphoneba.net/2563.html v8.2.0 http://www.zhinin.com/wondershare_filmora-mac.html ============================================================== for Littlstar http://docs.littlstar.com/plugins/servlet/mobile?contentId=2262863#content/view/2262863 Video Requirements H.264 High@5.1 or lower Max pixel width: 2560 Max frame rate: 60fps (最好是29.97) YUV420/NV12 color space 20Mbps bit rate or lower Audio Requirements Stereo Audio only AAC (Advanced Audio Coding) 320Kbps bit rate or lower Container Requirements File extensions: MP4, MOV No fragmented MP4 No DRM 15 min max duration 以上~ Littlstar不支援平面的3D格式,只支援180或360 而PSVR的媒體播放器不支援3D,只支援360 ============================================================== Make 3D Videos For PSVR Wat