對於任務,我被要求「創建一個名爲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
我會假設,如果你已經被授予一個類,你應該使用它。你怎麼做取決於它是如何實現的。 –