我在實現一個名爲MyTreeMap的TreeMap類,put方法給了我一些麻煩。在測試期間,不是更新已經存在的密鑰的值,而是完全清除節點。下面是代碼:把方法放在TreeMap的實現中
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) {
if(this.isEmpty()) {
this.key = key;
this.value = value;
this.size++;
setHeight();
return null;
}
else if(this.key.compareTo(key) == 0) {
V temp = this.value;
this.value = value;
return temp;
}
else if(this.key.compareTo(key) > 0) {
if(this.left == null) {
this.left = new MyTreeMap<K,V>(key,value,null,null);
this.size++;
if(left.height > right.height + 1 || right.height > left.height + 1)
restructure(this);
setHeight();
return null;
}
else
return this.left.put(key, value);
}
else {
if(this.right == null) {
this.right = new MyTreeMap<K,V>(key,value,null,null);
this.size++;
if(left.height > right.height + 1 || right.height > left.height + 1)
restructure(this);
setHeight();
return null;
}
else
return this.right.put(key, value);
}
}
這裏在測試中,第一的assertEquals傳遞,第二個沒,故障跟蹤被顯示在該行中
@Test
public void putTest2() {
TreeMap<String,LinkedList<Integer>> actual = new TreeMap<String,LinkedList<Integer>>();
MyTreeMap<String,LinkedList<Integer>> test = new MyTreeMap<String,LinkedList<Integer>>();
LinkedList<Integer> actualList = new LinkedList<Integer>();
actualList.add(0);
actualList.add(4);
LinkedList<Integer> testList = new LinkedList<Integer>();
testList.add(0);
testList.add(4);
actual.put("hello", actualList);
test.put("hello", actualList);
assertEquals(actual, test); //this part passes, indicating that it adds new keys correctly
LinkedList<Integer> tempList;
tempList = actual.get("hello");
tempList.add(6);
actual.put("hello", tempList);
test.put("hello", tempList);
assertEquals(actual, test); //this part fails, fail trace: expected:<{hello=[0,4,6,6]}> but was <[]>
}
}
評論如果你可以給我任何幫助解決這個錯誤,那會很有幫助。謝謝。
你實現了'K.compareTo()'嗎? – durron597
是的,除put方法之外,所有使用的方法均已實施且正在運行。 – user1547050
您是否使用調試器完成測試用例?應該很容易發現有什麼問題。換句話說...... ***你試過了什麼?*** –