示例1:使用HashSet类检查Set的子集
import java.util.HashSet;
import java.util.Set;
class Main {
public static void main(String[] args) {
// create the first set
Set numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("Numbers: " + numbers);
// create the second set
Set primeNumbers = new HashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("Prime Numbers: " + primeNumbers);
// check if primeNumbers is a subset of numbers
boolean result = numbers.containsAll(primeNumbers);
System.out.println("Is Prime Numbers is subset of Numbers? " + result);
}
}
输出
Numbers: [1, 2, 3, 4]
Prime Numbers: [2, 3]
Is Prime Numbers is subset of Numbers? true
在上面的示例中,我们创建了两个名为number和primeNumbers的集合。我们已经使用HashSet
类实现了该集合。注意这一行,
numbers.containsAll(primeNumbers);
在这里,我们使用了containsAll()
方法来检查primeNumbers是否为number的子集。
示例2:使用TreeSet类检查集合的子集
import java.util.TreeSet;
import java.util.Set;
class Main {
public static void main(String[] args) {
// create the first set
Set languages = new TreeSet<>();
languages.add("Java");
languages.add("JavaScript");
languages.add("Python");
languages.add("CSS");
System.out.println("Programming Languages: " + languages);
// create the second set
Set frontend = new TreeSet<>();
frontend.add("CSS");
frontend.add("JavaScript");
System.out.println("Frontend Languages: " + frontend);
// check if frontend is a subset of languages
boolean result = languages.containsAll(frontend);
System.out.println("Is frontend is subset of languages? " + result);
}
}
输出
Programming Languages: [CSS, Java, JavaScript, Python]
Frontend Languages: [CSS, JavaScript]
Is frontend is subset of languages? true
在这里,我们使用TreeSet
类实现了该集合。