Set.contains()如何决定它是否是一个子集?

Zoe*_*Zoe 6 java iterator set subset hashset

我希望下面的代码能给我一个子集和一个补充集.

但实际上,结果显示"错误:这不是一个子集!"

it.next()得到什么以及如何修改我的代码以获得我想要的结果?谢谢!

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

gja*_*ain 31

您可能希望set.containsAll(Collection <?> C)用于检查Collection(在本例中为Set)是否为'set'的子集.来自文档:http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#containsAll(java.util.Collection)

boolean containsAll(Collection c)

如果此set包含指定collection的所有元素,则返回true.如果指定的集合也是集合,则此方法如果是此集合的子集,则返回true.


mor*_*ano 5

你的问题就在这一部分:

set.contains(s)
Run Code Online (Sandbox Code Playgroud)

它不会做你认为它会做的事情,它不会将另一个作为参数Set来查看其成员是否包含在第一个中set。相反,它看起来传递的参数是否在集合中。

您需要迭代“包含”集合并用于set.contains(element)包含集合中的每个元素。