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

标签 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());
    }
}

最佳答案

您可能想使用 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)

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.

关于java - Set.contains() 如何决定它是否是一个子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17824140/

相关文章:

c++ - 谁应该拥有迭代器、我的数据类或该类中的实际列表?

python - 有没有办法为 random.uniform 设置开放和封闭端点?

Python按索引选择列表中的元素

algorithm - 如何在点集/二维形状中找到 "central" anchor ?

java - Intellij 和 MAVEN 之间 Junits 的代码覆盖率不匹配

java - 我如何从另一个类获取字符串?

c++ - 无需去交织即可在单个音频 channel 上运行

java - 使用正则表达式从句子中查找带有 [a-zA-Z] 的单词

java - 比较 Java 和 Jython 类型时的奇怪行为

java - Java HashSet 奇怪的迭代器行为