[英]Put method in an implementation of TreeMap
我正在實現一個名為MyTreeMap的TreeMap類,而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) {
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 <[]>
}
}
如果您能為我提供解決此錯誤的任何幫助,那將是有幫助的。 謝謝。
在這種情況下, assertEquals(a, b)
測試兩個Map
參數是否是同一對象 ,而不是它們包含相同的value 。
您的類和TreeMap
都沒有實現equals()
因此使用了Object
類的默認實現,它僅返回a == b
。
查看Hamcrest庫,以按價值有意義地比較集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.