简体   繁体   English

LinkedHashMap Java 8的JUnit顺序

[英]JUnit order of LinkedHashMap Java 8

i need to check full equality of two maps, including their order 我需要检查两张地图的完全相等性,包括其顺序

@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));
    }

All tests passed, with the output in console: 通过所有测试,并在控制台中输出:

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

Everywhere in the documentation it is written that LinkedHashMap is keeping order of insertion. 文档中到处都有LinkedHashMap保持插入顺序。 Than why does assertion of two same but different ordered maps give true? 那么为什么两个相同但不同的有序映射的断言为真呢? And what map should I take if equal order is important? 如果同等重要,我应该选择什么地图?

The definition of equals for a Map is that they have the same entry set, regardless of order. Mapequals定义是,它们具有相同的条目集,而不管顺序如何。

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. 如果给定对象也是一个映射并且两个映射表示相同的映射,则返回true。 More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). 更正式地说,如果m1.entrySet()。equals(m2.entrySet()),则两个映射m1和m2表示相同的映射。 This ensures that the equals method works properly across different implementations of the Map interface. 这样可确保equals方法可在Map接口的不同实现中正常工作。

If you want to assert identical iteration order, you could copy both iterations into Lists and compare the lists. 如果要声明相同的迭代顺序,则可以将两个迭代都复制到列表中并比较列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM