gpt4 book ai didi

java - LinkedHashMap Java 8 的 JUnit 顺序

转载 作者:行者123 更新时间:2023-11-30 02:45:37 25 4
gpt4 key购买 nike

我需要检查两个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com