How does Set.contains () decide if this is a subset or not?

I expect the following code to give me a subset and an extra set.

But in fact, the result shows that "Error: this is not a subset!"

What is it.next () and how to edit my code to get the result I want? Thanks!

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()); } } 
+6
source share
2 answers

Your problem in this part:

 set.contains(s) 

which does not do what you think it does, does not accept another Set as an argument to see if its members are contained in the first Set . It more likely looks if the argument is passed to Set.

You need to iterate over the β€œcontained” set and use set.contains(element) for each element of the contained set.

+2
source

You probably want to use set.containsAll(Collection <?> C) to check if Collection (Set, in this case) is a subset of "set". From the docs: http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#containsAll (java.util.Collection)

boolean contains all (collection c)

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

+21
source

Source: https://habr.com/ru/post/950142/


All Articles