[英]Put method of a TreeMap implementation
我正在開發TreeMap(稱為MyTreeMap)的實現,但是put方法遇到了很多麻煩。 我希望有人可以查看我的代碼,並向我指出發生錯誤的正確方向。
public class MyTreeMap<K extends Comparable<? super K>,V> extends AbstractMap<K,V> {
K key;
V value;
int height;
MyTreeMap<K,V> left,right;
int size;
public V put(K key, V value) {
int compareValue = this.key.compareTo(key);
if(!this.containsKey(key)) {
if(this.key == null) {
this.key = key;
this.value = value;
}
if(this.isLeaf() || this.isEmpty()) {
if(this.key.compareTo(key) > 0)
this.left = new MyTreeMap<K,V>(key,value,null,null);
else
this.right = new MyTreeMap<K,V>(key,value,null,null);
if(left.height > right.height + 1 || right.height > left.height + 1)
restructure(this);
this.size++;
setHeight();
return null;
}
else {
if(compareValue > 0)
return this.left.put(key, value);
else
return this.right.put(key, value);
}
}
else {
if(compareValue == 0) {
V temp = this.value;
this.value = value;
return temp;
}
else if(compareValue < 0)
return this.right.put(key, value);
else
return this.left.put(key, value);
}
}
我認為您的邏輯有點由內而外,結果比所需的要復雜得多:頂層if
應該查看compareValue
,而不是執行containsKey
檢查。
邏輯應為:
compareValue==0
則意味着您找到了正確的鍵,因此只需更新值並返回 PS:我建議在TreeMap中不允許使用空鍵,這會使您的生活更簡單,並且避免對鍵進行空值檢查
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.