[英]Java TreeMap implementation get and put methods
我正在編寫TreeMap的實現,並且在get和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;
private V get(K searchKey) {
if(this.isEmpty())
return null;//it needs an exception
if(this.key.compareTo(searchKey) == 0)
return this.value;
else if(this.key.compareTo(searchKey) > 0)
return this.left.get(searchKey);
else
return this.right.get(searchKey);
}
public V put(K key, V value) {
if(this.containsKey(key)) {
if(this.key.compareTo(key) == 0) {
V temp = this.value;
this.value = value;
return temp;
}
else if(this.key.compareTo(key) < 0)
return this.right.put(key, value);
else if(this.key.compareTo(key) > 0)
return this.left.put(key, value);
}
else {
if(this.isLeaf() || this.isEmpty()) {
if(this.key.compareTo(key) > 0) //this line gives NPE during tests
this.left = new MyTreeMap(key,value,null,null);
else
this.right = new MyTreeMap(key,value,null,null);
//check for balance and rebalance if needed
this.size++;
this.setHeight();
return null;
}
else {
if(this.key.compareTo(key) > 0)
return this.left.put(key, value);
else
return this.right.put(key, value);
}
}
}
最瘋狂的錯誤是put方法需要另一個return語句。 在代碼中檢查了很多遍,在我看來,情況並非如此,因為有一個return語句不需要任何布爾語句為真。
在測試put方法時,我得到了NPE。 我認為我的代碼存在一些非常重要的邏輯錯誤,因為我似乎無法弄清楚什么是錯誤的。 如果可以的話,請向我指出正確的方向來修復這些各種錯誤,這將對您有所幫助。 謝謝。
關於“額外” return
語句:
if(this.containsKey(key)) {
if(this.key.compareTo(key) == 0) {
V temp = this.value;
this.value = value;
return temp;
}
else if(this.key.compareTo(key) < 0)
return this.right.put(key, value);
else if(this.key.compareTo(key) > 0)
return this.left.put(key, value);
}
您的邏輯是要針對<0
, >0
和==0
檢查this.key.compareTo(key)
,以便涵蓋所有情況。 但這不是編譯器的情況,因為:
編譯器不知道this.key.compareTo(key)
的值在所有三個執行中是否都相同。 即使它具有檢查方法的智能,並且看到它不使用任何其他輸入來獲取結果(沒有),編譯器也無法知道另一個線程是否正在同時更改鍵的值。
即使您進行int value=this.key.compareTo(key)
並隨后對value
進行檢查,編譯器也不會檢查連續的if-elsif是否覆蓋所有值范圍。 無論如何,出於性能/並發性的原因,建議您使用這種方法只調用一次compareTo
。
最簡單的解決方法是將else if (this.key.compareTo(key) > 0)
else
(因為您應該知道是否執行了該塊是因為if必須為true)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.