java-HashMap分析,javahashmap
(一)雜湊演算法
雜湊演算法,將未經處理資料通過散列函數映射為較短的固定長度的二進位值,簡稱雜湊值。
hash演算法有兩個基本特點:可重複和無法復原。理論上計算出的雜湊值是可重複的,但好的散列函數基本不會出現這種情況。無法復原指,知道雜湊值無法推算出未經處理資料。
雜湊演算法一般用於快速尋找(如HashMap)和密碼編譯演算法(如MD5)。
(二)java中的hashcode
java中對象基類Object有hashcode方法,native調用預設返回對象記憶體位址,hashcode返回不定長的10進位數。
Java對於eqauls方法和hashCode方法是這樣規定的:1、如果兩個對象相同(equal),那麼它們的hashCode值一定要相同;2、如果兩個對象的hashCode相同,它們並不一定相同。
hashcode可以重寫,String重寫了hashcode。
public int hashCode() {int h = hash; int len = count;if (h == 0 && len > 0) { int off = offset; char val[] = value; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; }s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
使用 int 演算法,這裡 s[i] 是字串的第 i 個字元,n 是字串的長度,^ 表示求冪。(Null 字元串的雜湊碼為 0。)
(三)hashmap源碼分析
資料格式:數組和鏈表結合的拉鏈法雜湊表。
/** *整個HashMap的基本資料結構 */ transient HashMapEntry<K, V>[] table; static class HashMapEntry<K, V> implements Entry<K, V> { //put(key,value)中的key final K key; //put(key,value)中的value V value; //經過雜湊映射Function Compute出的hash值 final int hash; //指向下一個HashMapEntry HashMapEntry<K, V> next; HashMapEntry(K key, V value, int hash, HashMapEntry<K, V> next) { this.key = key; this.value = value; this.hash = hash; this.next = next; } .... }
public V put(K key, V value) { if (key == null) return putForNullKey(value); //防止品質較差的雜湊函數帶來過多的衝突(碰撞)問題,進一步使用映射函數產生值 int hash = hash(key.hashCode()); //計算出該hash屬於哪個數組位置座標 int i = indexFor(hash, table.length); //檢測該key是否已存在於數組為i的鏈表中 for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; //hash相同,key不一定相同 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; //從頭部插入該HashMapEntry對象 addEntry(hash, key, value, i); return null; }
(四)HashMap和HashTable的區別
1.繼承不同
Hashtable extends Dictionary
HashMap extends AbstractMap
2.同步
HashMap是非同步的,HashTable是同步的
3.插入值
HashMap鍵值允許為null,HashTable不允許
HashMap通過get方法擷取到null不代表不存在該key,必須用containsKey()方法來判斷。
HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("1", null); System.out.println(hashMap.get("1"));//null System.out.println(hashMap.get("2"));//null
JAVA HASHMAP 怎用
import java.util.*;
public class Test{
public static void main(String[] args){
HashMap map = new HashMap();
System.out.println("當前map中有" + map.size() + "個元素");
map.put("學習委員", "zhangsan");
map.put("生活委員", "lisi");
map.put("體育委員", "wangwu");
System.out.println("當前map中有" + map.size() + "個元素");
System.out.println("這班的生活委員是:" + map.get("生活委員"));
map.remove("生活委員");
System.out.println("當前map中有" + map.size() + "個元素");
}
}
java中HashMap使用
String