2011-12-12 194 views
6

很是怪異: A是一組和B是一套集:如何檢測一組集合是否包含另一個集合?

Set <String> A=new HashSet<String>(); 
Set <Set<String>> B=new HashSet<Set<String>>(); 

我添加的東西,對他們的

System.out.println(A) 

輸出:

[evacuated, leave, prepc_behind] 

和輸出

System.out.println(B) 

是:

[[leave, to, aux], [auxpass, were, forced], [leave, evacuated, prepc_behind]] 

,因爲它可以看出,集合B中的第三個元素等於設置A.所以,假設

if(B.contains(A)){...} 

應返回true,但顯然事實並非如此。問題是什麼?

更多詳細信息:

Pattern pattern = Pattern.compile("(.*?)\\((.*?)\\-\\d+,(.*?)\\-\\d+\\).*"); 
    for (int i = 0; i < list.size(); i++) { 
     Set <String> tp = new HashSet<String>(); 
     Matcher m = pattern.matcher(list.get(i).toString()); 
     if (m.find()) { 
      tp.add(m.group(1).toLowerCase()); 
      tp.add(m.group(2).toLowerCase()); 
      tp.add(m.group(3).toLowerCase()); 
     } 
     B.add(tp); 
    } 
    Set <String> A=new HashSet<String>(); 
    A.add("leave"); 
    A.add("evacuated"); 
    A.add("prepc_behind"); 
    System.out.println(A); 
    if(B.contains(A)){ 
    System.out.println("B contains A"); 
} 
+3

你是如何添加元素的?因爲'B.contains(A)'對我來說是正確的。 –

+0

對我來說也按預期工作(即返回true)。 –

+0

我有一個for循環,它使用:B.add(tp); tp是一個集合。 – Marcus

回答

-1

Set.contains(其他)​​如果一個元素屬於集等於其他返回true。

並且Set覆蓋equals()和hash()。如果兩個集合具有相同的元素,則Set.equals()將返回true。因此,如果A2屬於B,並且A2與A具有相同的元素,則包含(A)將返回true;

2

的基本思路(setA.contains(setB) == true)似乎很好地工作:

Set<String>  set1 = new HashSet<String>(); 
    Set<Set<String>> set2 = new HashSet<Set<String>>(); 
    Set<String>  tmpSet; 

    set1.add("one"); 
    set1.add("three"); 
    set1.add("two"); 

    tmpSet = new HashSet<String>(); 
    tmpSet.add("1"); 
    tmpSet.add("2"); 
    tmpSet.add("3"); 
    set2.add(tmpSet); 

    tmpSet = new HashSet<String>(); 
    tmpSet.add("one"); 
    tmpSet.add("two"); 
    tmpSet.add("three"); 
    set2.add(tmpSet); 

    System.out.println(set2.contains(set1)); // true 

我會大膽地猜測您正在捕獲更多的正則表達式,那麼你想。 嘗試將來自正則表達式和測試字符串的匹配轉換爲byte[]並相互檢查它們。

相關問題