2013-01-24 71 views
25

有可能,我只是沒有在這裏找到一個簡單的一行,但這是我的問題:ArrayList包含另一個ArrayList的

如何檢查是否一個ArrayList包含了所有在其他ArrayList中的對象。我期待(如果存在)中的線沿線的東西:

//INCORRECT EXAMPLE: 
if(one.contains(two)) 
{ 
    return true; 
} 
else 
{ 
    return false; 
} 

例如:

ArrayList one = {1, 2, 3, 4, 5} 

ArrayList two = {1, 2, 3} --> True 
ArrayList two = {} --> True 
ArrayList two = {1, 2, 3, 4, 5} --> True 
ArrayList two = {1, 5, 2} --> True 
ArrayList two = {1, 7, 4} --> False 
ArrayList two = {0, 1, 3} --> False 
ArrayList two = {4, 5, 6} --> False 
ArrayList two = {7, 8, 9} --> False 
+1

{1,3,2} =真或假? – cowls

+0

爲真。在這種情況下,謝謝你的錯誤更新 – Evorlor

+0

你想containsAll(已經是答案) – cowls

回答

49

java.util.Collection接口中有一種稱爲containsAll的方法。在您的設置one.containsAll(two)給出了所需的答案。

3

你的示例代碼沒有任何意義,但這裏有一個例子呢。

ArrayList<Integer> one, two; 
//initialize 
boolean good = true; 
for (int i = 0; i < two.size(); i ++) { 
    if (!(one.contains(two.get(i))) { 
     good = false; 
     break; 
    } 
} 

它只需通過所有two的元素和檢查的循環,看看他們在one

然後布爾值good包含您想要的值。

請參閱ArrayList#contains

編輯:哦,哇,我完全忘了containsAll。哦,如果你真的想了解它,這是一種替代方法。

+3

一旦它變成'假'你應該'打破'。沒有必要繼續檢查其餘的。 –

+0

@LeeMeador是的,謝謝 – Doorknob

+2

或者(而不是中斷)你可以這樣做: for(int i = 0; i MadcoreTom

11

每List接口:

myList.containsAll(...); 
10

看看containsAll(Collection<?> c)方法從List接口。我認爲這是你正在尋找的。

3

您可以使用列表的containsAll方法進行檢查。但是,這是一個線性操作。如果列表很大,你應該把它轉換爲HashSet,然後再進行containsAll

HashSet tmp = new HashSet(one); 
if (tmp.containsAll(two)) { 
    ... 
} 

如果one長度爲N和兩個長度爲M,該解決方案具有時間O(M+N)複雜性; 「普通」containsAll的複雜度爲O(M*N),可能會更糟糕。

2

下面是另一個例子使用containsAll()的,我已經用於斷言兩個數組中的JUnit測試等於:

List<String> expected = new ArrayList<String>(); 
expected.add("this"); 
expected.add("that"); 
expected.add("another"); 

List<String> actual = new ArrayListString(); 
actual.add("another"); 
actual.add("that"); 
actual.add("this"); 

Assert.assertTrue("The lists do not match!", expected.containsAll(actual)); 
相關問題