- 線程安全
- 不能存儲null到key和value
- HashTable中hash數組默認大小是11,增加的方式是 old*2+1。HashMap中hash數組的默認大小是16,而且一定是2的指數
區別
Hashtable
Hashmap
繼承、實現
Hashtable
extends Dictionary implements Map , Cloneable,Serializable HashMap
extends AbstractMap implements Map , Cloneable,Serializable 線程同步
已經同步過的可以安全使用
未同步的,可以使用Colletcions進行同步Map
Collections.synchronizedMap(Map m) 對null的處理
Hashtable table = new Hashtable();
table.put(null, "Null");
table.put("Null", null);
table.contains(null);
table.containsKey(null);
table.containsValue(null);
后面的5句話在編譯的時候不會有異常,可在運行的時候會報空指針異常具體原因可以查看源代碼
public synchronized V put(K key, V value) {
// Make sure the value is not null if (value == null) { throw new NullPointerException(); }
HashMap map = new HashMap();
map.put(null, "Null");map.put("Null", null);
map.containsKey(null);
map.containsValue(null);
以上這5條語句無論在編譯期,還是在運行期都是沒有錯誤的.
在HashMap中,null可以作為鍵,這樣的鍵只有一個;可以有一個或多個鍵所對應的值為null。當get()方法返回null值時,即可以表示 HashMap中沒有該鍵,也可以表示該鍵所對應的值為null。因此,在HashMap中不能由get()方法來判斷HashMap中是否存在某個鍵,而應該用containsKey()方法來判斷。
增長率
protected void rehash() { int oldCapacity = table.length; Entry[] oldMap = table; int newCapacity = oldCapacity * 2 + 1; Entry[] newMap = new Entry[newCapacity]; modCount++; threshold = (int)(newCapacity * loadFactor); table = newMap; for (int i = oldCapacity ; i-- > 0 ;) { for (Entry old = oldMap[i] ; old != null ; ) { Entry e = old; old = old.next; int index = (e.hash & 0x7FFFFFFF) % newCapacity; e.next = newMap[index]; newMap[index] = e; } } } void addEntry(int hash, K key, V value, int bucketIndex) {
Entry e = table[bucketIndex]; table[bucketIndex] = new Entry (hash, key, value, e); if (size++ >= threshold) resize(2 * table.length); } 哈希值的使用
HashTable直接使用對象的hashCode,代碼是這樣的:
public synchronized booleancontainsKey(Object key) {
Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index] ; e !=null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return true; } } return false; } HashMap重新計算hash值,而且用與代替求模
public boolean containsKey(Object key) { Object k = maskNull(key); int hash = hash(k.hashCode()); int i = indexFor(hash, table.length); Entry e = table[i]; while (e != null) { if (e.hash == hash && eq(k, e.key)) return true; e = e.next; } return false; }
1.Hashtable概要:實現Map接口的同步實現
1. HashMap概要:基于哈希表Map接口的非同步實現
2. HashMap代碼詳解:
- 線程不安全,線程安全請使用Hashtable
- 效率較好
- 提供null作為key或者value
2. HashMap代碼詳解:
- 默認 初始化
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; //默認是0.75
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);//擴容的門檻,存入的數據大于該值,容量擴充一倍
table = new Entry[DEFAULT_INITIAL_CAPACITY];//初始化數組,數組內容為Entry,存儲鏈表
init();
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; //默認是0.75
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);//擴容的門檻,存入的數據大于該值,容量擴充一倍
table = new Entry[DEFAULT_INITIAL_CAPACITY];//初始化數組,數組內容為Entry,存儲鏈表
init();
- 存入元素:
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);//如果key為null,直接把value放到數組第一位table[0]
int hash = hash(key.hashCode());//通過可以的hashcode計算對應的hash值
int i = indexFor(hash, table.length);//通過hash值,把entry對應到數組的位數計算出來
for (Entry<K,V> e = table[i]; e != null; e = e.next) {//如果該entry還包含下一個entry的引用,則繼續遍歷該鏈表
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {//如果key相同,則替換新的value到制定的key
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
if (key == null)
return putForNullKey(value);//如果key為null,直接把value放到數組第一位table[0]
int hash = hash(key.hashCode());//通過可以的hashcode計算對應的hash值
int i = indexFor(hash, table.length);//通過hash值,把entry對應到數組的位數計算出來
for (Entry<K,V> e = table[i]; e != null; e = e.next) {//如果該entry還包含下一個entry的引用,則繼續遍歷該鏈表
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {//如果key相同,則替換新的value到制定的key
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
- 讀取元素:
public V get(Object key) {
if (key == null)//key為null,直接從數組第一位拿數據
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)]; //直接通過key的hashcode計算出對應到數組的索引位,直接取數據,如果有鏈表繼續查找
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
if (key == null)//key為null,直接從數組第一位拿數據
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)]; //直接通過key的hashcode計算出對應到數組的索引位,直接取數據,如果有鏈表繼續查找
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
- 總結:
1. Vector概要:
- 默認長度為10
* Constructs an empty vector so that its internal data array
* has size {@code 10} and its standard capacity increment is
* zero.
*/
public Vector() {
this(10);
}
* has size {@code 10} and its standard capacity increment is
* zero.
*/
public Vector() {
this(10);
}
- 底層采用數組存儲:protected Object[] elementData;
- 線程安全
- 查詢效率比較高,比較適用于查詢
- 擴容的長度為初始長度的一半,建議初始化的時候設置已知的長度,免得容器自己去擴容,浪費空間以及效率
與ArrayList基本一樣,除了所有操作資源的方法都加了synchronized,保證線程同步
這里的源代碼就不詳解了,具體請參考容器-數組-ArrayList詳解。
1. ArrayList概要:
2. ArrayList代碼詳解:
/**
- 默認長度為10
this(10);
}
}
- 底層采用數組存儲:private transient Object[] elementData;
- 線程不安全,在多線程場景會出現問題,可以考慮使用Vector或者Collections.synchronizedList同步該容器
- 查詢效率比較高,比較適用于查詢
- 擴容的長度為初始長度的一半,建議初始化的時候設置已知的長度,免得容器自己去擴容,浪費空間以及效率
2. ArrayList代碼詳解:
- 增加元素
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
首先檢查數組是否已滿,如果滿了就開始擴容,擴容后的長度為原長度的1.5倍。elementData[size++] = e;
return true;
}
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
modCount++;//modCount表示數組的操作計數,用于iterator的時候與Count比較,防止迭代操作對add,remove等操作影響迭代操作
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) { //新插入元素后的長度大于老的長度,數組開始擴容
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;//新空間為原長度的1.5倍,等于是擴容了50%
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);//把之前的元素拷貝到新的數組 }
}
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
modCount++;//modCount表示數組的操作計數,用于iterator的時候與
expectedMod
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) { //新插入元素后的長度大于老的長度,數組開始擴容
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;//新空間為原長度的1.5倍,等于是擴容了50%
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);//把之前的元素拷貝到新的數組 }
}
- 刪除元素:
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
RangeCheck(index); //檢查索引是否溢出
modCount++; //操作計數
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,//復制原數組制定index+1到length-1的元素到elementData的index的索引位
numMoved);
elementData[--size] = null; // Let gc do its work//最后一位設置為null
return oldValue;
}
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
RangeCheck(index); //檢查索引是否溢出
modCount++; //操作計數
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,//復制原數組制定index+1到length-1的元素到elementData的index的索引位
numMoved);
elementData[--size] = null; // Let gc do its work//最后一位設置為null
return oldValue;
}
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}
- 獲取元素:
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
RangeCheck(index);
return (E) elementData[index]; //直接獲取數組的索引位
}
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
RangeCheck(index);
return (E) elementData[index]; //直接獲取數組的索引位
}