MCPcopy Create free account
hub / github.com/careercup/ctci / Hash

Class Hash

java/Chapter 8/Question8_10/Hash.java:5–61  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3import java.util.LinkedList;
4
5public class Hash<K, V> {
6 private final int MAX_SIZE = 5;
7 LinkedList<Cell<K, V>>[] items;
8
9 public Hash() {
10 items = (LinkedList<Cell<K, V>>[]) new LinkedList[MAX_SIZE];
11 }
12
13 public int hashCodeOfKey(K key) {
14 return key.toString().length() % items.length;
15 }
16
17 public void put(K key, V value) {
18 int x = hashCodeOfKey(key);
19 if (items[x] == null) {
20 items[x] = new LinkedList<Cell<K, V>>();
21 }
22 LinkedList<Cell<K, V>> collided = items[x];
23 for (Cell<K, V> c : collided) {
24 if (c.equivalent(key)) {
25 collided.remove(c);
26 break;
27 }
28 }
29
30 Cell<K, V> cell = new Cell<K, V>(key, value);
31 collided.add(cell);
32 }
33
34 public V get(K key) {
35 int x = hashCodeOfKey(key);
36 if (items[x] == null) {
37 return null;
38 }
39 LinkedList<Cell<K, V>> collided = items[x];
40 for (Cell<K, V> c : collided) {
41 if (c.equivalent(key)) {
42 return c.getValue();
43 }
44 }
45
46 return null;
47 }
48
49 public void debugPrintHash() {
50 for (int i = 0; i < items.length; i++) {
51 System.out.print(i + ": ");
52 LinkedList<Cell<K, V>> list = items[i];
53 if (list != null) {
54 for (Cell<K, V> cell : list) {
55 System.out.print(cell.toString() + ", ");
56 }
57 }
58 System.out.println("");
59 }
60 }
61}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected