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

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


例如,如果我有一个Model包含ArrayList包含Integer名为的对象的属性的类values,我想这样做:


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


斯蒂芬大帝
浏览 341回答 3
3回答

喵喵时光机

您正在寻找assertNotSame:预期和实际的断言没有引用相同的对象。

ABOUTYOU

为了满足您的要求,您必须将对象引用的断言与对象内容的断言结合起来。请注意,关于集合内容的断言不够充分:assertEquals(model1.values.size(), model2.values.size());Integer value1 = model1.values.get(0);Integer value2 = model2.values.get(0);assertEquals(value1, value2);仅声明集合的第一个元素显然是不够的,但是如果您首先断言所期望的是克隆集合中的单个元素。事实并非如此。相反,您应该依靠equals()将equals()set方法应用于元素集的集合的方法。使用Assert.assertNotSame()断言都Model和Model.values不引用同一个对象。然后Assert.assertEqual()用来断言Model.values集合在包含元素方面是相等的。// Create the original valueModel model1 = ...// Copy the original value into a new objectModel model2 = modelCopier(model1);// 1) Check that they don't refer the same objectAssert.assertNotSame(model1, model2);// 2)  Check that they don't refer the same objectAssert.assertNotSame(model1.values, model2.values);// 3) Check that their values properties contain the same values though!   Assert.assertEquals(model1.values, model2.values);

慕的地6264312

比较参考:assertTrue(model1.values != model2.values);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java