ในบทความนี้ เราจะเข้าใจวิธีตรวจสอบว่า Set หนึ่งเป็น Subset ของอีก Set หนึ่ง Set คือ Collection ที่ไม่สามารถมี duplicate elements ได้ มันเป็นแบบจำลองของ mathematical set abstraction อินเตอร์เฟซ Set มีเฉพาะเมธอดที่สืบทอดจาก Collection และเพิ่มข้อจำกัดว่าห้ามมี duplicate elements
ด้านล่างเป็นการสาธิต:
สมมติอินพุตคือ
First set: [90, 75, 60, 45] Second set: [90, 60]
เอาต์พุตที่ต้องการคือ
Is a sets sub-set of the other? true
อัลกอริทึม
Step 1 - START Step 2 - ประกาศตัวแปร Step 3 - กำหนดค่า Step 4 - สร้าง 2 Sets เพิ่มองค์ประกอบด้วย 'add' Step 5 - แสดง Sets บนคอนโซล Step 6 - สร้างตัวแปร Boolean เรียกเมธอด 'containsAll' บน set หนึ่งเทียบอีก set Step 7 - ตรวจสอบว่า set หนึ่งเป็น subset ของอีก set Step 8 - ถ้าใช่ คืนค่า True ไม่ใช่คืนค่า False Step 9 - แสดงผลบนคอนโซล Step 10 - Stop
ตัวอย่าง 1
ที่นี่ เรารวมทุกการดำเนินการภายใต้ฟังก์ชัน 'main'
import java.util.HashSet;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
Set input_set_1 = new HashSet<>();
input_set_1.add(45);
input_set_1.add(60);
input_set_1.add(75);
input_set_1.add(90);
System.out.println("The first set is defined as: " + input_set_1);
Set input_set_2 = new HashSet<>();
input_set_2.add(60);
input_set_2.add(90);
System.out.println("The second set is defined as: " + input_set_2);
boolean result = input_set_1.containsAll(input_set_2);
System.out.println("\nIs a sets sub-set of the other? \n" + result);
}
}
ผลลัพธ์
The required packages have been imported The first set is defined as: [90, 75, 60, 45] The second set is defined as: [90, 60] Is a sets sub-set of the other? true
ตัวอย่าง 2
ที่นี่ เราบรรจุการดำเนินการลงในฟังก์ชันแสดง object-oriented programming
import java.util.HashSet;
import java.util.Set;
public class Demo {
static void is_subset(Set input_set_1, Set input_set_2){
boolean result = input_set_1.containsAll(input_set_2);
System.out.println("\nIs a sets sub-set of the other? \n" + result);
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
Set input_set_1 = new HashSet<>();
input_set_1.add(45);
input_set_1.add(60);
input_set_1.add(75);
input_set_1.add(90);
System.out.println("The first set is defined as: " + input_set_1);
Set input_set_2 = new HashSet<>();
input_set_2.add(60);
input_set_2.add(90);
System.out.println("The second set is defined as: " + input_set_2);
is_subset(input_set_1, input_set_1);
}
}
ผลลัพธ์
The required packages have been imported The first set is defined as: [90, 75, 60, 45] The second set is defined as: [90, 60] Is a sets sub-set of the other? true