用BST实现HashMap

Posted warmland

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用BST实现HashMap相关的知识,希望对你有一定的参考价值。

把核心的逻辑都放在Node里面

所以Node的代码是:

 1 public class MapNode<K extends Comparable<K>, V> {
 2     private K key;
 3     private V value;
 4     private MapNode<K, V> left;
 5     private MapNode<K, V> right;
 6 
 7     public MapNode(K key, V value) {
 8         this.key = key;
 9         this.value = value;
10     }
11 
12     public V put(K key, V value) {
13         if(this.key.compareTo(key) == 0) {
14             V oldValue = this.value;
15             this.value = value;
16             return oldValue;
17         } else if(this.key.compareTo(key) < 0) {
18             if(right == null) {
19                 right = new MapNode(key, value);
20                 return null;
21             } else {
22                 return right.put(key, value);
23             }
24         } else {
25             if(left == null) {
26                 left = new MapNode(key, value);
27                 return null;
28             } else {
29                 return left.put(key, value);
30             }
31         }
32     }
33 
34     public V get(K key) {
35         if(this.key.compareTo(key) == 0) {
36             return this.value;
37         } else if(this.key.compareTo(key) < 0) {
38             return right == null? null: right.get(key);
39         } else {
40             return left == null? null: left.get(key);
41         }
42     }
43 }

Map部分的代码是:

 1 public class ImplementHashmapUsingBST<K extends Comparable<K>, V> {
 2     MapNode<K, V> root;
 3     int size;
 4 
 5     public ImplementHashmapUsingBST() {
 6         size = 0;
 7     }
 8 
 9     public V get(K key) {
10         if(root == null) {
11             return null;
12         }
13         return root.get(key);
14     }
15 
16     public V put(K key, V value) {
17         if(root == null){
18             root = new MapNode(key, value);
19             return null;
20         } else {
21             V oldValue = root.put(key, value);
22             if(oldValue == null) {
23                 size++;
24                 return null;
25             }
26             return oldValue;
27         }
28     }
29 
30     public static void main(String[] args) {
31         ImplementHashmapUsingBST<String, String> sample = new ImplementHashmapUsingBST();
32         sample.put("Apple", "Fruit");
33         sample.put("Pork", "Meat");
34         System.out.println(sample.get("Apple"));
35     }
36 
37 }

 

以上是关于用BST实现HashMap的主要内容,如果未能解决你的问题,请参考以下文章

HashMap深度解析

JDK源码阅读之 HashMap

包含不同片段的HashMap(或ArrayList)

hashmap冲突的解决方法以及原理分析:

编程实践用 go 语言实现线程安全的 hashmap

大厂面试必问!HashMap 怎样解决hash冲突?