我有一种情况,我想知道给定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
喵喵时光机
ABOUTYOU
慕的地6264312
相关分类