簡體   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