mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 17:29:31 +08:00
Optimize Hashmap implementation (#3533)
This commit is contained in:
@ -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;
|
||||||
|
Reference in New Issue
Block a user