javascript中實現相容JAVA的hashCode演算法代碼分享_基礎知識

來源:互聯網
上載者:User

在java中一個hashCode演算法,可以用來計算一個字串的hash值,今天一個朋友突然問俺能不能在js中計算hashCode,要求和java的hashCode計算結果一樣。

對於java的hashCode,以前到現在也一直沒有瞭解過其演算法,不過猜想應該也不會太難,於是現在java中寫了這段代碼進行測試:
運行結果:899755

按下Ctrl鍵點擊hashCode方法名跟進去看了下其演算法,發現是很簡單的幾句代碼,如下所示:

複製代碼 代碼如下:

public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;

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

這下好,簡單移植過去到js裡就應該ok了。於是寫出如下JS代碼:

複製代碼 代碼如下:

<script type="text/javascript">
function hashCode(str){
         var h = 0, off = 0;
         var len = str.length;
         for(var i = 0; i < len; i++){
             h = 31 * h + str.charCodeAt(off++);
         }
         return h;
     }
     alert(hashCode('瀋陽'));
   </script>

運行結果:899755

OK,與java計算結果一樣。本以為這麼就搞定了,然後想著再隨便找個串測試下:

“瀋陽瀋陽啊”,在JAVA中運行結果為:1062711668,然而到js中成了:26832515444。

狂暈,這隨便一試就有問題了!後思考片刻,突然想到Java中int長度好像是21億左右,js中就沒這限制了。問題應該就是在這裡了,於是對之前的方法做了一點改造:

複製代碼 代碼如下:

<script>
function hashCode(str){
         var h = 0, off = 0;
         var len = str.length;
         for(var i = 0; i < len; i++){
             h = 31 * h + str.charCodeAt(off++);
         }
     var t=-2147483648*2;
     while(h>2147483647){
       h+=t
     }
         return h;
     }
alert(hashCode('瀋陽瀋陽啊'));</script>

再次測試!OK!大功告成。沒有什麼技術含量,一點小總結
2013-02-19更新,上面那個效率比較低下,當內容很長的時候會當掉,下面的代碼是最佳化後的代碼:

複製代碼 代碼如下:

<script>
    function hashCode(str) {
        var h = 0;
        var len = str.length;
        var t = 2147483648;
        for (var i = 0; i < len; i++) {
            h = 31 * h + str.charCodeAt(i);
            if(h > 2147483647) h %= t;//java int溢出則模數
        }
        /*var t = -2147483648 * 2;
        while (h > 2147483647) {
            h += t
        }*/
        return h;
    }
    alert(hashCode('C#同一時間N個線程在並發執行,其餘在隊列中如何?')); //1107373715
</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.