这是一个简单的 HashMap 实现,其中 BST 作为存储桶。这个 Map 的基本实现展示了 put() 和 get() 如何从 BST 存储桶支持的 Map 中获取数据。这个 BST 实现是不平衡的。理想情况下,对于生产应用程序,此 BST 应使用红黑树算法进行平衡,以缩短寻道时间。
与链表相比,使用平衡 BST 实现的存储桶,我们能够将 Get(key) 时间从 O(n) 提高到 O(log n)。
public class HashMapWithBST {
private Node[] nodes;
private static final int MAX_CAPACITY = 41;
public HashMapWithBST() {
nodes = new Node[MAX_CAPACITY];
}
/**
* If key is a non-null object then return the hash code of key modulo hash map size as value. If key is null then return 0.
*
* @param key
* @return hash
*/
public int getHash(String key) {
if(key == null) {
return 0;
}
int hash = key.hashCode();
hash = hash >>> 16; // Spread the higher bits
hash = hash % MAX_CAPACITY;
return hash;
}
/**
* In case of collisions, put the new key-value pair in a BST based on key comparisons.
*
* @param key
* @param value
*/
public void put(String key, String value) {
int hashOfKey = getHash(key);
final Node newNode = new Node(key, value);
if(nodes[hashOfKey] == null) {
nodes[hashOfKey] = newNode;
} else {
Node root = nodes[hashOfKey];
try {
addToBSTBucket(root, newNode);
} catch(Exception e ) {
e.printStackTrace();
}
}
}
/**
* If a collision happens while adding a node to Hashmap, add new node to the hashed bucket represented with a BST.
*
* @param root root of BST bucket
* @param newNode New Node to be added in BST bucket
*/
private void addToBSTBucket(Node root, final Node newNode) {
if(root == null) {
root = newNode;
return;
}
Node currentNode = root;
Node parentNode = root;
while(true) {
parentNode = currentNode;
if(newNode.key.compareTo(currentNode.key) == 0) {
// if key values are same then just overwrite the vale in same node as duplicate keys are not allowed in this map
currentNode.value = newNode.value;
return;
} else if(newNode.key.compareTo(currentNode.key) < 0) {
currentNode = currentNode.left;
if(currentNode == null) {
parentNode.left = newNode;
return;
}
} else {
currentNode = currentNode.right;
if(currentNode == null) {
parentNode.right = newNode;
return;
}
}
}
}
/**
* Get the value for a particular key. If no key found then return null.
*
* @param key
* @return value or null
*/
public String get(String key) {
Node node = nodes[getHash(key)];
if(node != null) {
return getValueFromBST(node, key);
}
return null;
}
private String getValueFromBST(Node root, String key) {
if(key == null) {
return null;
}
while(root != null) {
if(key.equals(root.key)) {
return root.value;
} else if(key.compareTo(root.key) < 0) {
root = root.left;
} else {
root = root.right;
}
}
return null;
}
private static class Node {
private String key;
private String value;
private Node left;
private Node right;
public Node(String key, String value) {
this.key = key;
this.value = value;
}
}
}
完整代码位于此处:https ://github.com/prabhash1785/DataStructures/blob/d842d07e1fc3bf7e1caed72eb6b0744a719a9bc6/src/com/prabhash/java/algorithms/datastructures/HashMapWithBST.java