java - Put 方法在 TreeMap 的实现中

标签 java junit 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 参数是否是同一个对象,而不是它们包含相同的值

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

看看 Hamcrest library用于按值(value)有意义地比较集合。

关于java - Put 方法在 TreeMap 的实现中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13221192/

相关文章:

java - 使用堆栈和队列对数组进行排序

java - 在 Maven 项目中与依赖项共享单元测试

java - 如何通过自定义Struts类型转换器转换列表项的字段?

java - 在 Pig 中按名称获取字段?

java - 使用 Junit 进行数据驱动测试

java - 使用 Mockito 进行 stub 时出现 NullPointerException

javascript - 在谷歌图表 TreeMap 中显示值

Java:SortedMap、TreeMap、Comparable?如何使用?

Java map 内容对比

java - NetCDF 4.5 Java NetCDF 文件版本 4 的问题 + HDF 的旧代码不起作用