diff --git a/src/main/java/core/basesyntax/MyHashMap.java b/src/main/java/core/basesyntax/MyHashMap.java index d9beffedf..293b15b85 100644 --- a/src/main/java/core/basesyntax/MyHashMap.java +++ b/src/main/java/core/basesyntax/MyHashMap.java @@ -1,19 +1,97 @@ package core.basesyntax; +import java.util.Objects; + public class MyHashMap implements MyMap { + private static final int DEFAULT_CAPACITY = 16; + private static final float LOAD_FACTOR = 0.75f; + private static final int GROWTH_FACTOR = 2; + + private Node[] 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 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 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[] oldTable = table; + table = new Node[oldTable.length * GROWTH_FACTOR]; + size = 0; + + for (Node node : oldTable) { + while (node != null) { + put(node.key, node.value); + node = node.next; + } + } + } + + private static class Node { + private K key; + private V value; + private Node next; + + private Node(K key, V value) { + this.key = key; + this.value = value; + } } }