用BST實現HashMap

來源:互聯網
上載者:User

標籤:get   ble   rabl   compare   extends   shm   map   private   public   

把核心的邏輯都放在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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.