이 기사에서는 집합이 다른 집합의 하위 집합인지 확인하는 방법을 이해합니다. Set은 중복 요소를 포함할 수 없는 Collection입니다. 수학적 집합 추상화를 모델링합니다. Set 인터페이스는 Collection에서 상속된 메서드만 포함하고 중복 요소가 금지된다는 제한을 추가합니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
First set: [90, 75, 60, 45] Second set : [90, 60]
원하는 출력은 -
Is a sets sub-set of the other? true
알고리즘
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Create two Sets, and add elements to it using the ‘add’ method. Step 5 - Display the Sets on the console. Step 6 - Create a Boolean variable and call the ‘containsAll’ method on one set with respect to the other. Step 7 - This checks if one set is a subset of the other. Step 8 - If yes, it returns True, else False. Step 9 - Display the result on the console. 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<Integer> 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<Integer> 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
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
import java.util.HashSet;
import java.util.Set;
public class Demo {
static void is_subset(Set<Integer> input_set_1, Set<Integer> 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<Integer> 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<Integer> 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