【问题标题】:Put method in an implementation of TreeMap将方法放入 TreeMap 的实现中
【发布时间】:2012-11-04 17:48:46
【问题描述】:

我正在实现一个名为 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 <[]>
}

}

如果您可以帮助我解决此错误,那将很有帮助。谢谢。

【问题讨论】:

  • 你实现K.compareTo()了吗?
  • 是的,除了 put 方法之外,所有使用的方法都已实现并正常工作。
  • 您是否使用调试器逐步完成了测试用例?应该很容易发现问题所在。换句话说... 你试过什么?

标签: java junit treemap


【解决方案1】:

在这种情况下,assertEquals(a, b) 测试两个 Map 参数是否相同的对象,而不是它们包含相同的值

你的类和TreeMap都没有实现equals(),所以使用Object类的默认实现,它只返回a == b

查看Hamcrest library 以有意义地按价值比较集合。

【讨论】:

  • 感谢您的帮助,我只使用 assertEquals 并比较两者,因为它适用于大多数情况。 actual.equals(test) 虽然返回 false,这意味着实际上代码中存在错误,而不仅仅是 junit 测试。
猜你喜欢
  • 1970-01-01
  • 2013-10-31
  • 2021-01-21
  • 2017-07-06
  • 2015-03-26
  • 1970-01-01
  • 2016-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多