java - LinkedHashMap Java 8 的 JUnit 顺序

标签 java junit

我需要检查两个 map 的完全相等性,包括它们的顺序

@Test
    public void test(){
        Map<String, Integer> actual = new LinkedHashMap<>();
        actual.put("longer", 1);
        actual.put("first", 1);
        actual.put("thebiggest", 1);

        Map<String, Integer> expected = new LinkedHashMap<>();
        expected.put("thebiggest", 1);
        expected.put("longer", 1);
        expected.put("first", 1);

        System.out.println("===expected");
        expected.entrySet().stream().forEach(n->System.out.println(n.getKey()));
        System.out.println("===actual");
        actual.entrySet().stream().forEach(n->System.out.println(n.getKey()));

        assertEquals(expected, actual);
        assertTrue(expected.equals(actual));
    }

所有测试均已通过,控制台输出:

===expected
thebiggest
longer
first
===actual
longer
first
thebiggest

文档中到处都写到 LinkedHashMap 保持插入顺序。那么为什么两个相同但不同的有序映射的断言给出 true 呢? 如果平等顺序很重要,我应该采取什么 map ?

最佳答案

definition of equals for a Map是它们具有相同的条目集,无论顺序如何。

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

如果您想断言相同的迭代顺序,您可以将两个迭代复制到列表中并比较列表。

关于java - LinkedHashMap Java 8 的 JUnit 顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40287381/

相关文章:

java - SpringFox Swagger - 模型中的可选和必填字段

java - 以关键字作为名称截断表

DAO类Junit测试的Java配置(Spring5+Hibernate5)

java - DAO 设计模式与 DBUnit 代码

java - Java maven spring 框架的 Restful API 不工作

java - System.err﹕javax.net.ssl.SSLPeerUnverifiedException : No peer certificate

java - 在 JUnit 测试中,有没有一种方法可以确保所有断言都已执行?

java - 使用@Async 方法的 JUnit 回滚事务

java - 在 native c/c++ 代码中发生崩溃时,JVM 中的设置忽略 JRE 错误消息?

java - 按钮未出现在 JFrame 中