Created
March 29, 2017 03:59
-
-
Save linnykoleh/e1fc17042c1a629be7b3aa93406492db to your computer and use it in GitHub Desktop.
Hash map put node to array by key's hashcode
This file contains 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
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