I 'm novice in Algorithm. I read and aware that big-O of put(K key, V value) in Hashmap is O(1). When I went to core of HashMap class
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//...
if ((p = tab[i = (n - 1) & hash]) == null)
//...
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
// ...
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// ...
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
// ...
}
}
...
return null;
}
As you can see, when adding new item to hashmap, it will iterate max n (all item in hashmap) with "For Loop" above:
for (int binCount = 0; ; ++binCount) {
Now, big-O of For Loop here is O(n) --> Why big-O of put(K key, V value) in HashMap can be O(1) ? Where do I understand wrongly ?
Thanks very much.