Mi aspetto che il codice seguente mi fornisca un sottoinsieme e un set complementare.In che modo Set.contains() decide se si tratta di un sottoinsieme oppure no?
Ma in realtà, il risultato mostra che "Errore: questo non è un sottoinsieme!"
Cosa ottiene it.next() e come modificare il mio codice per ottenere il risultato che desidero? Grazie!
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());
}
}
È necessario conoscere Imposta apri prima di utilizzare Imposta. Si prega di coprire il mio tutorial [Vita interna di HashSet] (http://volodial.blogspot.com/2013/07/internal-life-of-hashset-in-java.html) –
@VolodymyrLevytskyi Il tuo link è rotto, è l'articolo ancora disponibile altrove? – Noumenon