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を取得します。何が悪いのか理解できないように見えるので、私のコードにはかなり重大な論理エラーがあると思います。これらのさまざまなエラーを修正するために正しい方向に私を向けていただければ、それは役に立ちます。ありがとうございました。