Menu
CoddyTech

子集与超集

本课属于 Coddy Java 学习旅程的“逻辑与流程”单元。第 33 课,共 59 课。

子集是一个集合,其中的每个元素也都包含在另一个集合中。超集是包含另一个集合所有元素的集合。

首先,创建两个 HashSet:

HashSet<String> setA = new HashSet<>();
setA.add("apple");
setA.add("banana");
HashSet<String> setB = new HashSet<>();
setB.add("apple");
setB.add("banana");
setB.add("cherry");

使用 containsAll() 方法:

boolean isSubset = setB.containsAll(setA);
System.out.println("setA is a subset of setB: " + isSubset);
// 输出:setA is a subset of setB: true

同样,setB 是 setA 的超集,因为它包含 setA 的每个元素。

challenge icon

挑战

简单

创建一个名为 checkSubsetSuperset 的方法,接收两个字符串 HashSet 作为输入:

  • setA 和 setB

该方法应执行以下操作:

  1. 使用 containsAll() 检查 setA 是否为 setB 的子集,并打印:

    setA is a subset of setB: <true/false>
  2. 检查 setB 是否为 setA 的超集(这是同一项检查),并打印:

    setB is a superset of setA: <true/false>

亲手试试

import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static void checkSubsetSuperset(HashSet<String> setA, HashSet<String> setB) {
        // 在这里编写你的代码
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 读取 setA 的 JSON 字符串(例如 ["apple","banana"])
        String setAString = scanner.nextLine();
        // 读取 setB 的 JSON 字符串(例如 ["apple","banana","cherry"])
        String setBString = scanner.nextLine();
        
        Type setType = new TypeToken<HashSet<String>>(){}.getType();
        HashSet<String> setA = new Gson().fromJson(setAString, setType);
        HashSet<String> setB = new Gson().fromJson(setBString, setType);
        
        checkSubsetSuperset(setA, setB);
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: Java 在线编译器