经典Hash实现(采用拉链法处理冲突)(一)

2014-11-24 11:07:21 · 作者: · 浏览: 0
class StorePageMap {
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
private Entry[] table;
/**
* The number of key-value mappings contained in this identity hash map.
*/
private int size;
/**
* The next size value at which to resize (capacity * load factor).
* @serial
*/
private int threshold;
/**
* Constructs an empty HashMap with the default initial capacity
* (16) and the default load factor (0.75).
*/
StorePageMap() {
threshold = 12;
table = new Entry[17];
}
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map.
*/
final int size() {
return size;
}
/**
* Returns true if this map contains no key-value mappings.
*
* @return true if this map contains no key-value mappings.
*/
final boolean isEmpty() {
return size == 0;
}
/**
* Returns the first StorePage for the given key.
*/
final TableStorePage get(long key) {
int i = (int)(key % table.length);
Entry e = table[i];
while (true) {
if (e == null)
return null;
if (e.key == key)
return e.value;
e = e.next;
}
}
/**
* Returns true if this map contains a StorePage for the
* specified key.
*
*/
final boolean containsKey(long key) {
return (get(key) != null);
}
/**
* Add the StorePage with the key. Multiple StorePage for the same key are valid.
* The cause are multiple changes in one transaction. With SavePoints a rollback to a older
* StorePage is valid.

* The latest StorePage is placed at first pos.
*/
final TableStorePage add(long key, TableStorePage value) {
int i = (int)(key % table.length);
table[i] = new Entry(key, value, table[i]);
if (size++ >= threshold)
resize(2 * table.length);
return null;
}
/**
* Rehashes the contents of this map into a new array with a
* larger capacity. This method is called automatically when the
* number of keys in this map reaches its threshold.
*
* If current capacity is MAXIMUM_CAPACITY, this method does not
* resize the map, but but sets threshold to Integer.MAX_VALUE.
* This has the effect of preventing future calls.
*
* @param newCapacity the new capacity, MUST be a power of two;
* must be greater than current capacity unless current
* capacity is MAXIMUM_CAPACITY (in which case value
* is irrelevant).
*/
final private void resize(int newCapacity) {
Entry[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int)(newCapacity * 0.75f);
}
/**
* Transfer all entries from current table to newTable.
*/
final private void transfer(Entry[] newTable) {
Entry[] src = table;
int newCapacity = newTable.length;
for (int j = 0; j < src.length; j++) {
Entry e = src[j];
if (e != null) {
src[j] = null;
do {
Entry next = e.next;
e.next = null;