簡體   English   中英

檢查一個 ArrayList 是否包含另一個 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的內容時,我同時獲得了temptemp1 我怎樣才能解決這個問題?

您可以使用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是一種檢查此集合是否包含給定集合的所有元素的方法。 在這種情況下:

  • 這個集合有 1 個元素,它是一個List<String>
  • 給定的集合有 3 個元素,分別是"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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM