2016-03-11 56 views
0

對於任務,我被要求「創建一個名爲TreeMap的類,該類使用BinarySearchTree類來實現地圖」。我們提供了一系列接口和類來擴展和實現。寫我自己的'TreeMap'類 - 什麼擴展和/或實現?

作業的第一步要求「創建一個名爲TreeEntry的內部類來存儲條目,包括一個構造函數和任何強制方法」。

我們給出的接口包括BinaryTree<T>,Entry<K, V>,Map<K, V>等等。

我們給出的課程是BinarySearchTree<T extends Comparable<T>> implements Iterable<T>等等。

我正在努力確定如何申報我的TreeMap。是否應該延伸BinarySearchTree,或者執行Map,還是兩者兼而有之?

到目前爲止,我想出了是public class TreeMap<K, V> implements Map<Comparable<K>, V>,然後將創建TreeMap嵌套類,但我不明白,我會「使用BinarySearchTree類來實現地圖」?我在TreeMap課程中創建了一個新的BinarySearchTree<TreeEntry<K, V>>

編輯

這是我至今寫:

public class TreeMap<K, V> implements Map<Comparable<K>, V> { 

    private class TreeEntry<K, V> implements Entry<K, V>, Comparable<K> { 

     private K key; 
     private V value; 

     public TreeEntry(K key, V value) { 
      this.key = key; 
      this.value = value; 
     } 

     @Override 
     public int compareTo(K otherKey) { 
      if (this.key.equals(otherKey)) { 
       return 0; 
      } 
      else if (this.key > otherKey) { 
       return 1; 
      } 
      else { 
       return -1; 
      } 
     } 

     @Override 
     public K getKey() { 
      // TODO Auto-generated method stub 
      return null; 
     } 

     @Override 
     public V getValue() { 
      // TODO Auto-generated method stub 
      return null; 
     } 

     @Override 
     public V setValue(V value) { 
      // TODO Auto-generated method stub 
      return null; 
     } 

    } 
} 

我相信我沒有正確地實現Comparable<K>,因爲我得到一個錯誤的說法行else if (this.key > otherKey)The operator > is undefined for the argument type(s) K, K

+1

我會假設,如果你已經被授予一個類,你應該使用它。你怎麼做取決於它是如何實現的。 –

回答

0

將BinarySearchTree用作實現目前是一項任務。這可能是你目前的想法或者是有人如何去做的建議。如果你從它那裏繼承,並且在以後的時間點,當成千上萬的客戶使用你的TreeMap並且你決定BinarySearchTree不是完美的實現時,那麼你將不能再改變它。

這是因爲有人可能都用它作爲

BinarySearcTree<X,Y> map = new TreeMap<>(); 

現在怎麼辦?你堅持使用BinarySearchTree的繼承。但是如果你「只」實現Map,那麼你可以在任何時候改變這個類的實現,而不會給客戶帶來問題。

+0

感謝您的幫助。我已經開始按照您所概述的來編寫我的實現了,但是在我的'TreeMap'中使Keys可比。在原文中查看我的編輯。 – KOB

+0

java沒有任何運算符重載。所以你不能爲你的關鍵類定義運算符「>」。 java的方法是實現Comparable並實現compareTo方法。然後你可以做public int compareTo(K other){return this.key.compareTo(other.key);} – EasterBunnyBugSmasher

相關問題