[CC150v5] 8.10 Implement a Hashmap - Shuatiblog.com
Design and implement a hash table which uses chaining (linked lists) to handle collisions.
The main part of this is to use an array of list structure like this:
LinkedList<Cell<K, V>>[] items;
int size;
LinkedList<Cell<K, V>>[] items;
public HashMapCC150(int num) {
this.size = num;
items = (LinkedList<Cell<K, V>>[]) new LinkedList[10];
}
public V get(K k) {
int hashValue = this.calculateHashCode(k);
if (items[hashValue] == null) {
items[hashValue] = new LinkedList<Cell<K, V>>();
return null;
}
for (Cell<K, V> cell : items[hashValue]) {
if (k.equals(cell.getKey())) {
return cell.getValue();
}
}
return null;
}
public V put(K k, V v) {
int hashValue = this.calculateHashCode(k);
if (items[hashValue] == null) {
items[hashValue] = new LinkedList<Cell<K, V>>();
}
for (Cell<K, V> cell : items[hashValue]) {
if (k.equals(cell.getKey())) {
items[hashValue].remove(cell);
break;
}
}
Cell<K, V> newItem = new Cell<K, V>(k, v);
items[hashValue].add(newItem);
return null;
}
public V remove(K k) {
// not written
return null;
}
private int calculateHashCode(K k) {
return k.toString().length() % size;
}
Read full article from [CC150v5] 8.10 Implement a Hashmap - Shuatiblog.com