[英]how can a generic be <Map.Entry<KeyType,ValueType>>
我收到一個問題:
通過存儲TreeSet <Map.Entry<KeyType,ValueType>>
類型的數據成員來編寫TreeMap類的實現。
我很難使我像Treeset這樣的樹形類+實現Map接口,它們的含義是“存儲類型為TreeSet<<Map.Entry<KeyType,ValueType>>
的數據成員”
以及泛型如何為<Map.Entry<KeyType,ValueType>>
通過存儲
TreeSet <Map.Entry<KeyType,ValueType>>
類型的數據成員來編寫TreeMap
類的實現。
通過“編寫TreeMap類的實現” ,我將其解釋為以類似於內置TreeMap
類的行為來實現自己的類的含義,即NavigableMap
接口的實現。
通過“ 通過存儲X類型的數據成員 ”,我將其解釋為具有X類型字段的類的含義。
因此,您需要實現此類:
public class MyTreeMap<KeyType, ValueType> implements NavigableMap<KeyType, ValueType> {
private TreeSet<Map.Entry<KeyType, ValueType>> data;
// your code here
}
為了方便起見,以下是一些(簡單)方法:
public Set<Map.Entry<KeyType, ValueType>> entrySet() {
return this.data;
}
public void clear() {
this.data.clear();
}
public int size() {
return this.data.size();
}
UPDATE
我對TreeSet
解釋是使用一個Comparator
,該Comparator
通過鍵比較Entry
,以便您可以執行以下操作(偽代碼):
public ValueType get(Object key) {
Entry<...> dummy = new DummyEntry<...>(key);
Entry<...> found = this.data.ceiling(dummy);
if (found != null && comparator.compare(found, dummy) == 0)
return found.getValue();
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.