Skip to content
Open
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
73 changes: 71 additions & 2 deletions src/main/java/core/basesyntax/MyHashMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,87 @@

public class MyHashMap<K, V> implements MyMap<K, V> {

private static final int DEFAULT_CAPACITY = 16;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private static final int CAPACITY_MULTIPLIER = 2;
private Node<K, V>[] table;
private int size;
private int threshold;
private final float loadFactor;

public MyHashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
this.table = new Node[DEFAULT_CAPACITY];
this.threshold = (int) (DEFAULT_CAPACITY * loadFactor);
}

@Override
public void put(K key, V value) {

if (size >= threshold) {
resize();
}
int index = getIndex(key);
Node<K, V> node = table[index];
for (Node<K, V> curr = node; curr != null; curr = curr.next) {
if (key == curr.key || (key != null && key.equals(curr.key))) {
curr.value = value;
return;
}
}
table[index] = new Node<>(key, value, node);
size++;
}

@Override
public V getValue(K key) {
int index = getIndex(key);
for (Node<K, V> curr = table[index]; curr != null; curr = curr.next) {
if (key == curr.key || (key != null && key.equals(curr.key))) {
return curr.value;
}
}
return null;
}

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

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

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

private int getIndex(K key) {
Comment on lines +52 to +68

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This violates checklist item #5: 'Private methods and classes should be after public ones in your class.' Please move this private method and getIndex() after all public methods (e.g., after getSize()).

if (key == null) {
return 0;
}
return Math.abs(key.hashCode()) % table.length;
}

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

Node(K key, V value, Node<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
}


}
Loading