Skip to content
Open

Dev #1706

Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 79 additions & 1 deletion src/main/java/core/basesyntax/MyHashMap.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,97 @@
package core.basesyntax;

import java.util.Objects;

public class MyHashMap<K, V> implements MyMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private static final float LOAD_FACTOR = 0.75f;
private static final int GROWTH_FACTOR = 2;

private Node<K, V>[] table;
private int size;

public MyHashMap() {
table = new Node[DEFAULT_CAPACITY];
}

@Override
public void put(K key, V value) {
if (size >= table.length * LOAD_FACTOR) {
resize();
}

int index = getIndex(key);
Node<K, V> current = table[index];

if (current == null) {
table[index] = new Node<>(key, value);
size++;
return;
}

while (true) {
if (Objects.equals(current.key, key)) {
current.value = value;
return;
}

if (current.next == null) {
break;
}

current = current.next;
}

current.next = new Node<>(key, value);
size++;
}

@Override
public V getValue(K key) {
int index = getIndex(key);
Node<K, V> current = table[index];

while (current != null) {
if (Objects.equals(current.key, key)) {
return current.value;
}

current = current.next;
}

return null;
}

@Override
public int getSize() {
return 0;
return size;
}

private int getIndex(K key) {
return key == null ? 0 : Math.abs(key.hashCode() % table.length);
}

private void resize() {
Node<K, V>[] oldTable = table;
table = new Node[oldTable.length * GROWTH_FACTOR];
size = 0;

for (Node<K, V> node : oldTable) {
while (node != null) {
put(node.key, node.value);
node = node.next;
}
}
}

private static class Node<K, V> {
private K key;
private V value;
private Node<K, V> next;

private Node(K key, V value) {
this.key = key;
this.value = value;
}
}
}
Loading