2013-07-24 17 views
6

私は次のコードが私にサブセットと補完セットを与えると期待しています。Set.contains()はサブセットかどうかをどのように決定しますか?

実際、結果は「エラー:これはサブセットではありません!」と表示されます。

it.next()が取得し、私が望む結果を得るためにコードを修正する方法は? ありがとう!あなたはそれがないと思う何をしません

set.contains(s) 

が、それはそのメンバーが中に含まれているかどうかを確認するために、引数として別のSetを取ることはありません。

package Chapter8; 

import java.util.HashSet; 
import java.util.Iterator; 
import java.util.Set; 

public class Three { 
    int n; 
    Set<Integer> set = new HashSet<Integer>(); 

    public static void main(String args[]) { 
     Three three = new Three(10); 
     three.display(three.set); 
     Set<Integer> test = new HashSet<Integer>(); 
     Iterator<Integer> it = three.set.iterator(); 
     while(it.hasNext()) { 
      test.add(it.next()); 
      three.display(test); 
      three.display(three.complementarySet(test)); 
     } 

    } 

    boolean contains(Set<Integer> s) { 
     if (this.set.contains(s)) 
      return true; 
     else 
      return false; 
    } 

    Set<Integer> complementarySet(Set<Integer> s) { 
     if(this.set.contains(s)){ 
      Set<Integer> result = this.set; 
      result.removeAll(s); 
      return result; 
     } 
     else { 
      System.out.println("Error: This is not a subset!"); 
      return null; 
     } 
    } 

    Three() { 
     this.n = 3; 
     this.randomSet(); 
    } 

    Three(int n) { 
     this.n = n; 
     this.randomSet(); 
    } 

    void randomSet() { 
     while(set.size() < n) { 
      set.add((int)(Math.random()*10)); 
     } 
    } 

    void display(Set<Integer> s) { 
     System.out.println("The set is " + s.toString()); 
    } 
} 
+0

Setを使用する前にSet APIを知っておく必要があります。私のチュートリアル[HashSetの内部生活](http://volodial.blogspot.com/2013/07/internal-life-of-hashset-in-java.html) –

+0

@VolodymyrLevytskyiあなたのリンクは壊れています、記事まだ他の場所で利用できますか? – Noumenon

答えて

2

あなたの問題は、この部分にあります最初のset。それは渡された引数がSetにあるかどうかを調べます。

"含まれている"セットを反復処理し、含まれているセットの各エレメントにset.contains(element)を使用する必要があります。

20

Collection(この場合はSet)が 'set'のサブセットであるかどうかをチェックする場合は、おそらくset.containsAll(Collection <?> C)を使用します。ドキュメントから:http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#containsAll(java.util.Collection)

boolean containsAll(Collection c)

Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set, this method returns true if it is a subset of this set.

関連する問題