Java - 如何检查两个 ArrayList 是否是唯一对象(即使它们具有相同的值)?

标签 java arraylist collections

我有一个例子,我想知道给定的 ArrayList 是否是与另一个 ArrayList 不同的对象,即使它们的列表中包含相同的对象。我正在测试包含 ArrayList 的父对象的一些复制逻辑,我想确保这里的 future 开发人员不会在逻辑期间简单地重新分配数组列表。

例如,如果我有一个 Model 类,其中包含一个 ArrayList 属性,该属性包含名为 valuesInteger 对象,我想这样做:

// 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/

相关文章:

Java Collections - 高效搜索日期时间范围

java - removeAll 似乎影响了它的论点

java - JDBC批量插入耗时较长

java - JvisualVM 中的采样器和探查器有什么区别?

java - 介意帮助第一次遇到减速带的新人吗?

java - 将 JSONArray 转换为 arrayList

java - Vector or Synchronized LinkedList?哪个更好用?

java - hibernate 时自加入

java - 如何将 HashMap 添加到 ArrayList

Java ArrayList,如何在使用 contains() 时忽略对象中的值