繁体   English   中英

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

[英]Java - How to check if two ArrayLists are unique objects (even if they have the same values)?

我有一种情况,我想知道给定的ArrayList是否是与另一个ArrayList不同的对象,即使它们在列表中都包含相同的对象也是如此。 我正在测试包含ArrayList的父对象的某些复制逻辑,并且我想确保此处的未来开发人员不要在逻辑期间简单地重新分配数组列表。

例如,如果我有一个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方法:

比较指定对象与此列表是否相等。 当且仅当指定对象也是一个列表,并且两个列表具有相同的大小,并且两个列表中所有对应的元素对相等时,才返回true。 (如果(e1 == null?e2 == null:e1.equals(e2)),则两个元素e1和e2相等。)换句话说,如果两个列表包含相同顺序的相同元素,则两个列表定义为相等。 。 此定义确保equals方法可在List接口的不同实现中正常工作。

https://docs.oracle.com/javase/7/docs/api/java/util/List.html

您正在寻找assertNotSame

预期和实际的断言未引用同一对象。

为了满足您的要求,您必须将对象引用的断言与对象内容的断言结合起来。

请注意,关于集合内容的断言不够充分:

assertEquals(model1.values.size(), model2.values.size());

Integer value1 = model1.values.get(0);
Integer value2 = model2.values.get(0);

assertEquals(value1, value2);

仅声明集合的第一个元素显然是不够的,但是如果您首先断言所期望的是克隆集合中的单个元素。 事实并非如此。
相反,您应该依赖于集合的equals()方法,该方法将equals()应用于元素集。

使用Assert.assertNotSame()可以断言ModelModel.values都不引用同一对象。
然后使用Assert.assertEqual()断言Model.values集合在包含元素方面是相等的。

// Create the original value
Model model1 = ...

// Copy the original value into a new object
Model model2 = modelCopier(model1);

// 1) Check that they don't refer the same object
Assert.assertNotSame(model1, model2);

// 2)  Check that they don't refer the same object
Assert.assertNotSame(model1.values, model2.values);

// 3) Check that their values properties contain the same values though!   
Assert.assertEquals(model1.values, model2.values);

比较参考:

assertTrue(model1.values != model2.values);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM