Java 使用 JUnit 比较 ArrayLists 是否相等的简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1512689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:40:21  来源:igfitidea点击:

Easy way to compare ArrayLists for equality using JUnit?

javajunit

提问by Alex Baranosky

What is an easy way to compare ArrayLists for equality using JUnit? Do I need to implement the equality interface? Or is there a simple JUnit method that makes it easier?

使用 JUnit 比较 ArrayLists 是否相等的简单方法是什么?我需要实现相等接口吗?或者是否有一个简单的 JUnit 方法可以使它更容易?

采纳答案by starblue

You need to do nothing special for list equality, just use assertEquals.

您不需要为列表相等做任何特别的事情,只需使用 assertEquals。

ArrayList and other lists implement equals() by checking that all objects in the corresponding positions of the lists are equal, using the equals() method of the objects. So you might want to check that the objects in the list implement equals correctly.

ArrayList 和其他列表通过使用对象的 equals() 方法检查列表相应位置的所有对象是否相等来实现 equals()。因此,您可能需要检查列表中的对象实现是否正确。

回答by Tom Hawtin - tackline

You might want to check the documentation for List.equals.

您可能需要查看List.equals.

回答by Adriaan Koster

I think this might be a slightly too easy answer (although it is correct). Testing ArrayLists for equals implies you have given thought to equality of the elements. If the elements are Integers that is all fine. But if they are instances of your own domain classes, then you should be made aware of the pitfalls surrounding equality (and cloning). Please check out:

我认为这可能是一个过于简单的答案(尽管它是正确的)。测试 ArrayLists 的 equals 意味着您已经考虑过元素的相等性。如果元素是整数,那一切都很好。但是,如果它们是您自己的域类的实例,那么您应该意识到围绕平等(和克隆)的陷阱。请查看:

http://www.artima.com/lejava/articles/equality.html

http://www.artima.com/lejava/articles/equality.html

for a good set of tips about implementing equality. On an aside: If you ever need to clone objects, consider the use of copy constructors instead of implementing cloneable. Cloneable introduces a whole set of problems you might not expect.

有关实施平等的一套很好的技巧。顺便说一句:如果您需要克隆对象,请考虑使用复制构造函数而不是实现可克隆。Cloneable 引入了一系列您可能意想不到的问题。