Optimize Hashmap implementation (#3533)

This commit is contained in:
Kumaraswamy B G
2022-10-17 20:06:09 +05:30
committed by GitHub
parent d5f8e5f87a
commit 8855cf9525

View File

@ -2,14 +2,14 @@ package com.thealgorithms.datastructures.hashmap.hashing;
public class HashMap { public class HashMap {
private int hsize; private final int hsize;
private LinkedList[] buckets; private final LinkedList[] buckets;
public HashMap(int hsize) { public HashMap(int hsize) {
buckets = new LinkedList[hsize]; buckets = new LinkedList[hsize];
for (int i = 0; i < hsize; i++) { for (int i = 0; i < hsize; i++) {
buckets[i] = new LinkedList(); buckets[i] = new LinkedList();
// Java requires explicit initialisaton of each object // Java requires explicit initialization of each object
} }
this.hsize = hsize; this.hsize = hsize;
} }
@ -59,31 +59,22 @@ public class HashMap {
} }
private Node findEnd(Node n) { private Node findEnd(Node n) {
if (n.getNext() == null) { while (n.getNext() != null) {
return n; n = n.getNext();
} else {
return findEnd(n.getNext());
} }
return n;
} }
public Node findKey(int key) { public Node findKey(int key) {
if (!isEmpty()) { if (!isEmpty()) {
return findKey(first, key); Node temp = first;
} else { if (temp.getKey() == key) return temp;
System.out.println("List is empty");
return null;
}
}
private Node findKey(Node n, int key) { while ((temp = temp.getNext()) != null) {
if (n.getKey() == key) { if (temp.getKey() == key) return temp;
return n; }
} else if (n.getNext() == null) {
System.out.println("Key not found");
return null;
} else {
return findKey(n.getNext(), key);
} }
return null;
} }
public void delete(int key) { public void delete(int key) {
@ -95,8 +86,6 @@ public class HashMap {
} else { } else {
delete(first, key); delete(first, key);
} }
} else {
System.out.println("List is empty");
} }
} }
@ -132,7 +121,7 @@ public class HashMap {
public static class Node { public static class Node {
private Node next; private Node next;
private int key; private final int key;
public Node(int key) { public Node(int key) {
next = null; next = null;