LinkedHashMap Java 8的JUnit顺序 [英] JUnit order of LinkedHashMap Java 8

查看:73
本文介绍了LinkedHashMap Java 8的JUnit顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在文档中的每个地方都写明LinkedHashMap保持插入顺序.那么为什么两个相同但不同的有序映射的断言却为真呢? 如果相等的顺序很重要,我应该选择什么地图?

Everywhere in the documentation it is written that LinkedHashMap is keeping order of insertion. 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.

将指定对象与此映射进行比较以确保相等.如果给定对象也是一个映射,并且两个映射表示相同的映射,则返回true.更正式地说,如果m1.entrySet().equals(m2.entrySet()),则两个映射m1和m2表示相同的映射.这样可以确保equals方法可在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.

如果要声明相同的迭代顺序,可以将两个迭代都复制到列表中并比较列表.

If you want to assert identical iteration order, you could copy both iterations into Lists and compare the lists.

这篇关于LinkedHashMap Java 8的JUnit顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆