2016-09-28 174 views
1

我有一個列表的列表,我想添加一個列表到它,而不是重複。在其他這樣做,我想檢查列表是否已經包含在主列表中。我寫了這樣的事情檢查ArrayList是否包含另一個ArrayList作爲元素

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。我怎樣才能解決這個問題?

+0

你應該做'Main.add(new ArrayList (temp));'。直接添加temp會設置一個對temp變量(對象)的引用,這不是你想要的。 – progyammer

回答

1

這裏的問題是你對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]?由於兩個列表具有相同的大小,並且它們的所有元素都相等,所以它包含它。

+0

完美;那完美的工作。謝謝你的細節 – user3841581

2

您可以使用該方法List#contains(),因爲contains將檢查是等於提供ArrayList這將在這裏是如此的temp.equals(temp1)回報trueArrayList實例,因爲該方法的AbstractListequals比較其內容和這裏的內容那些ArrayList是平等的。

if(!Main.contains(temp1)) // check if temp1 is already in Main 
{ 
    Main.add(temp1); 
} 
+0

完美的工作;謝謝 – user3841581

1

既然你想避免重複列表(而不是檢查內部列表的元素),只需使用Main.contains代替Main.containsAll

這將檢查Main列表是否已經包含您要添加的元素的列表。

0

如果約爲ArrayList<Integer>,你會怎麼做?有一種名爲的方法。要檢查主列表是否包含某個對象(另一個列表),只需調用此函數將其作爲參數傳遞給它。

相關問題