1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| public class Hashing<K, V> { private static final int DEFAULT_CAPACITY = 16; private static final float LOAD_FACTOR = 0.75f; private Entry<K, V>[] table; private int size; public Hashing() { table = new Entry[DEFAULT_CAPACITY]; } public void put(K key, V value) { if (key == null) { throw new IllegalArgumentException("Key cannot be null"); } int index = hash(key); Entry<K, V> entry = table[index]; while (entry != null) { if (entry.getKey().equals(key)) { entry.setValue(value); return; } entry = entry.getNext(); } Entry<K, V> newEntry = new Entry<>(key, value, table[index]); table[index] = newEntry; size++; if (size >= LOAD_FACTOR * table.length) { resize(); } } public V get(K key) { if (key == null) { throw new IllegalArgumentException("Key cannot be null"); } int index = hash(key); Entry<K, V> entry = table[index]; while (entry != null) { if (entry.getKey().equals(key)) { return entry.getValue(); } entry = entry.getNext(); } return null; } public void remove(K key) { if (key == null) { throw new IllegalArgumentException("Key cannot be null"); } int index = hash(key); Entry<K, V> prev = null; Entry<K, V> entry = table[index]; while (entry != null) { if (entry.getKey().equals(key)) { if (prev == null) { table[index] = entry.getNext(); } else { prev.setNext(entry.getNext()); } size--; return; } prev = entry; entry = entry.getNext(); } } public int size() { return size; } private int hash(K key) { return Math.abs(key.hashCode()) % table.length; } private void resize() { Entry<K, V>[] oldTable = table; table = new Entry[table.length * 2]; size = 0; for (Entry<K, V> entry : oldTable) { while (entry != null) { put(entry.getKey(), entry.getValue()); entry = entry.getNext(); } } } private static class Entry<K, V> { private K key; private V value; private Entry<K, V> next; private Entry(K key, V value, Entry<K, V> next) { this.key = key; this.value = value; this.next = next; } public K getKey() { return key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } public Entry<K, V> getNext() { return next; } public void setNext(Entry<K, V> next) { this.next = next; } } }
|