我有一个例子,我想知道给定的 ArrayList
是否是与另一个 ArrayList
不同的对象,即使它们的列表中包含相同的对象。我正在测试包含 ArrayList
的父对象的一些复制逻辑,我想确保这里的 future 开发人员不会在逻辑期间简单地重新分配数组列表。
例如,如果我有一个 Model
类,其中包含一个 ArrayList
属性,该属性包含名为 values
的 Integer
对象,我想这样做:
// Create the original value
Model model1 = ...
// Copy the original value into a new object
Model model2 = modelCopier(model1);
// Check that they are not equal objects
assertNotEquals(model1, model2);
// Check that their values properties are not equal objects
assertNotEquals(model1.values, model2.values);
// Check that their values properties contain the same values though!
assertEquals(model1.values.size(), model2.values.size());
Integer value1 = model1.values.get(0);
Integer value2 = model2.values.get(0);
assertEquals(value1, value2);
这应该证明我们正在复制 Model
对象及其 values
属性,但是列表中的 值是相等的。
现在这失败了,因为 assertNotEquals(model1.values, model2.values)
失败了,这是有道理的,因为 List
类覆盖了 equals
这样的方法:
Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, 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.
https://docs.oracle.com/javase/7/docs/api/java/util/List.html
最佳答案
您正在寻找assertNotSame
:
Asserts that expected and actual do not refer to the same object.
关于Java - 如何检查两个 ArrayList 是否是唯一对象(即使它们具有相同的值)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51230341/