Check If Two Lists are Equal in Java – 在Java中检查两个列表是否相等

最后修改: 2016年 7月 18日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this short article we’ll focus on the common problem of testing if two List instances contain the same elements in exactly the same order.

在这篇短文中,我们将重点讨论测试两个List实例是否以完全相同的顺序包含相同的元素这一常见问题。

List is an ordered data structure so the order of elements matters by design.

List是一个有序的数据结构,所以元素的顺序在设计上很重要。

have a look at an excerpt from the List#equals Java documentation:

来看看List#equalsJava文档的摘录。

… two lists are defined to be equal if they contain the same elements in the same order.

……如果两个列表以相同的顺序包含相同的元素,则被定义为相等。

This definition ensures that the equals method works properly across different implementations of the List interface.

这个定义保证了equals方法在List接口的不同实现中正常工作。

We can use this knowledge when writing assertions.

我们可以在编写断言时使用这些知识。

In the following code snippets, we will be using the following lists as example inputs:

在下面的代码片断中,我们将使用以下列表作为输入示例。

List<String> list1 = Arrays.asList("1", "2", "3", "4");
List<String> list2 = Arrays.asList("1", "2", "3", "4");
List<String> list3 = Arrays.asList("1", "2", "4", "3");

2. JUnit

2.JUnit

In a pure JUnit test, the following assertions will be true:

在一个纯粹的JUnit测试中,以下断言将是真的。

@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
    Assert.assertEquals(list1, list2);
    Assert.assertNotSame(list1, list2);
    Assert.assertNotEquals(list1, list3);
}

3. TestNG

3.TestNG

When using TestNG’s assertions they will look very similarly to JUnit’s assertions, but it’s important to notice that the Assert class comes from a different package:

当使用TestNG的断言时,它们看起来与JUnit的断言非常相似,但需要注意的是,em>Assert类来自一个不同的包。

@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
    Assert.assertEquals(list1, list2);
    Assert.assertNotSame(list1, list2);
    Assert.assertNotEquals(list1, list3);
}

4. AssertJ

4.AssertJ

If you like to use AssertJ, it’s assertions will look as follows:

如果你喜欢使用AssertJ,它的断言将看起来如下。

@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
    assertThat(list1)
      .isEqualTo(list2)
      .isNotEqualTo(list3);

    assertThat(list1.equals(list2)).isTrue();
    assertThat(list1.equals(list3)).isFalse();
}

5. Conclusion

5.结论

In this article, we have explored how to test if two List instances contain the same elements in the same order. The most important part of this problem was the proper understanding of how the List data structure is designed to work.

在这篇文章中,我们探讨了如何测试两个List实例是否以相同的顺序包含相同的元素。这个问题最重要的部分是正确理解List数据结构是如何设计的。

All code examples can be found on GitHub.

所有的代码例子都可以在GitHub上找到。