Created
May 23, 2021 18:22
-
-
Save algomaster99/52d3c7cbbadd0c341a0fd1c3e9e40ca2 to your computer and use it in GitHub Desktop.
Couldn't we do without `equals`? I think only `hashCode` is sufficient.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.diffmin; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Objects; | |
public class TestMain { | |
public static void main(String args[]) { | |
HashMapImpl newHashMap = new HashMapImpl(); | |
newHashMap.add(4, "a"); // [4: a] | |
newHashMap.add(7, "b"); // [4: a, 7: b] | |
newHashMap.add(4, "c"); // [4: c, 7: b] | |
newHashMap.add(10, "d"); // [4: c, 7: b, 10: d] | |
newHashMap.add(7, "e"); // [4: c, 7: e, 10: d] | |
newHashMap.add(20, "f"); // [4: c, 7: e, 10: d, 20: f] | |
} | |
} | |
class HashMapImpl { | |
private final int capacity = 16; | |
private final List<Node<Integer, String>> hashMap; | |
HashMapImpl() { | |
hashMap = new ArrayList<>(); | |
for (int i=0; i<capacity; ++i) { | |
hashMap.add(null); | |
} | |
} | |
public void add(Integer key, String value) { | |
Node<Integer, String> newNode = new Node<>(key, value); | |
int index = key % capacity; | |
if (hashMap.get(index) == null) { | |
hashMap.remove(index); | |
hashMap.add(index, newNode); | |
} else { | |
Node<Integer, String> oldNode = hashMap.get(index); | |
Node<Integer, String> parent; | |
do { | |
if (oldNode.hashCode() == newNode.hashCode()) { | |
oldNode.key = newNode.key; | |
oldNode.value = newNode.value; | |
return; | |
} | |
parent = oldNode; | |
oldNode = oldNode.next; | |
} while (oldNode != null); | |
parent.next = newNode; | |
} | |
} | |
public String get(Integer key) throws IllegalStateException { | |
int hash = Objects.hash(key); | |
int index = key % capacity; | |
if (hashMap.get(index) != null) { | |
Node<Integer, String> oldNode = hashMap.get(index); | |
while (oldNode != null) { | |
if (oldNode.hashCode() == hash) { | |
return oldNode.value; | |
} | |
oldNode = oldNode.next; | |
} | |
throw new IllegalStateException(key + " not found"); | |
} else { | |
throw new IllegalStateException(key + " not found."); | |
} | |
} | |
} | |
class Node<K,V> { | |
K key; | |
V value; | |
Node<K,V> next; | |
Node(K key,V value) { | |
this.key = key; | |
this.value = value; | |
this.next = null; | |
} | |
@Override | |
public int hashCode() { | |
return Objects.hash(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment