判斷一個數是否是偶數,你真的仔細去考慮過么


   怎樣判斷一個數是否是偶數,正常學的差不多的都會知道說用這個數去%2,我們可以挖一下,這個模2是怎么出來的,是通過&1,這個是底層的算法,然后我們再挖深下,&1的底層是,假如3&1也就是011和001做與運算,二進制轉換十進制怎么整的,不就是2的n-1次方么,所以只要計算第一位的與運算就知道這個數是否是奇數還是偶數了

  其實Javase的一些源碼也可以看到很多這些影子,

  static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

    /**
     * Returns index for hash code h.
     */
    static int indexFor(int h, int length) {
        return h & (length-1);
    }
  public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
//將key做hash算法
int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; }
 
         

 

 

     從這段代碼可以看出,hashmap通過將key做hash算法,然后通過hash值映射到內存地址,取得key所對應的數據。平時都知道hashMap的底層數據結構用的是數組,這么整下來數組的下標索引也就是內存地址了,通過上述代碼看到hash()的實現全部基於位運算,而位運算比算數,邏輯運算快,通過indexFor()將hash值與數組長度按位取與得到數組索引,返回數組的索引直接通過數組下標便可以取得對應的值,內存訪問的速度也快,也可以看到hashMap的性能可見一斑

      通過判斷某個數是否是偶數,去理解indexFor()到底為何這么用,這就是為何說源碼是最好的教科書的所在


免責聲明!

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



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