[英]Check if an ArrayList contains the same element as another ArrayList
[英]Checking if an ArrayList contains another ArrayList as element
我有一個列表列表,我想向其中添加一個列表,不要重復。 在其他方面,我想檢查該列表是否已包含在主列表中。 我寫過這樣的東西
import java.util.ArrayList;
public class Test{
public static void main(String [] args)
{
ArrayList<ArrayList<String>> Main = new ArrayList<>();
ArrayList<String> temp = new ArrayList<>();
temp.add("One");
temp.add("Two");
temp.add("Three");
Main.add(temp);// add this arraylist to the main array list
ArrayList<String> temp1 = new ArrayList<>();
temp1.add("One");
temp1.add("Two");
temp1.add("Three");
if(!Main.containsAll(temp1)) // check if temp1 is already in Main
{
Main.add(temp1);
}
}
}
當我打印Main
的內容時,我同時獲得了temp
和temp1
。 我怎樣才能解決這個問題?
您可以使用List#contains()
因為contains
將檢查與提供的ArrayList
相等的ArrayList
實例,這里就是這種情況,因為temp.equals(temp1)
返回true
因為AbstractList
的方法equals
比較它們的內容在這里,這些ArrayList
的內容是相等的。
if(!Main.contains(temp1)) // check if temp1 is already in Main
{
Main.add(temp1);
}
由於您想避免重復列表(而不是檢查內部列表的元素),只需使用Main.contains
而不是Main.containsAll
。
這將檢查Main
列表是否已經包含一個包含您將要添加的元素的列表。
這里的問題是您對containsAll
和列表列表的使用感到困惑。
containsAll
是一種檢查此集合是否包含給定集合的所有元素的方法。 在這種情況下:
List<String>
;"One
, "Two"
和"Three"
。 很明顯,這個只包含List<String>
(即["First, "Two", "Three"]
)的集合不包含這 3 個元素;它只包含這三個元素的列表。
所以你真正想要的不是containsAll
,而是contains
,即你想檢查你的列表是否包含另一個列表(而不是它的元素)。
以下工作:
if (!Main.contains(temp1)) {
Main.add(temp1);
}
並將導致Main
為[[One, Two, Three]]
,只添加一次。
附帶的問題是:為什么它有效? 現在,問題是:我的List<List<String>>
是否包含[[One, Two, Three]]
,包含這個List<String>
,即[One, Two, Three]
? 由於兩個列表在大小相同並且它們的所有元素都相等時是相等的,因此它確實包含它。
如果是關於ArrayList<Integer>
你會怎么做? 有一個名為contains()
的方法。 要檢查您的主列表是否包含某個對象(另一個列表),只需調用此函數將其作為參數傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.