Skip to content

Instantly share code, notes, and snippets.

@linnykoleh
Created March 29, 2017 03:59
Show Gist options
  • Save linnykoleh/e1fc17042c1a629be7b3aa93406492db to your computer and use it in GitHub Desktop.
Save linnykoleh/e1fc17042c1a629be7b3aa93406492db to your computer and use it in GitHub Desktop.
Hash map put node to array by key's hashcode
public V put(K key, V value) {
int hashCodeKey = hash(key);
return putVal(hashCodeKey, key, value);
}
private V putVal(int hashCodeKey, K key, V value) {
int newHashTableSize;
int indexForNode;
Node<K,V> nodeByHashCodeKey;
if (hashTable == null || hashTable.length == 0) {
hashTable = new Node[DEFAULT_INITIAL_CAPACITY];
}
newHashTableSize = hashTable.length;
indexForNode = (newHashTableSize - 1) & hashCodeKey;
nodeByHashCodeKey = hashTable[indexForNode];
if (nodeByHashCodeKey == null) {
hashTable[indexForNode] = new Node<>(hashCodeKey, key, value, null);
} else {
Node<K,V> next;
K keyForNodeByHashCodeKey = nodeByHashCodeKey.key;
if (nodeByHashCodeKey.hashCodeKey == hashCodeKey && keyForNodeByHashCodeKey == key || (key != null && key.equals(keyForNodeByHashCodeKey))) {
next = nodeByHashCodeKey;
} else {
while(true){
next = nodeByHashCodeKey.next;
if (next == null) {
nodeByHashCodeKey.next = new Node<>(hashCodeKey, key, value, null);
break;
}
if (next.hashCodeKey == hashCodeKey) {
keyForNodeByHashCodeKey = next.key;
if(keyForNodeByHashCodeKey == key || ( key != null && key.equals(keyForNodeByHashCodeKey) )) {
break;
}
}
nodeByHashCodeKey = next;
}
}
if (next != null) {
V oldValue = next.value;
if (oldValue != null) {
next.value = value;
}
return oldValue;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment