2013-07-24 10 views
6

Oczekuję, że poniższy kod da mi podzbiór i zestaw uzupełniający.W jaki sposób Set.contains() decyduje, czy jest to podzbiór czy nie?

Ale w rzeczywistości wynik pokazuje, że "Błąd: To nie podzbiór!"

What it.next() uzyskać i jak poprawić mój kod, aby uzyskać wynik, który chcę? Dzięki!

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

Musisz znać Ustaw api przed użyciem Set. Proszę opisać mój tutorial [Życie wewnętrzne programu HashSet] (http://volodial.blogspot.com/2013/07/internal-life-of-hashset-in-java.html) –

+0

@VolodymyrLevytskyi Twój link jest zepsuty, to jest artykuł nadal dostępne w innym miejscu? – Noumenon

Odpowiedz

2

Twój problem jest w tej części:

set.contains(s) 

że nie robi tego, co myślisz, że to robi, to nie bierze jako argument innej Set aby sprawdzić, czy jej członkowie są zawarte w pierwszy set. Raczej wygląda, jeśli argument przekazał go w zestawie.

Należy powtórzyć zestaw "zawierający" i użyć set.contains(element) dla każdego elementu w zestawie zawierającym.

20

Prawdopodobnie chcesz użyć set.containsAll(Collection <?> C) do sprawdzenia, czy Zbiór (w tym przypadku zestaw) jest podzbiorem "zestawu". Od dokumentów: 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.

Powiązane problemy