수동 루프로 검증
이전 단계에서는 부분 집합을 확인하기 위해 편리한 containsAll() 메서드를 사용했습니다. containsAll()은 효율적이지만, 루프를 사용하여 이 검사를 수동으로 수행하는 방법을 이해하는 것이 도움이 됩니다. 이렇게 하면 컬렉션 메서드가 내부적으로 어떻게 작동하는지 더 깊이 이해할 수 있습니다.
SubsetCheck.java 파일에 부분 집합 검사를 수동으로 수행하는 새 메서드를 추가해 보겠습니다. WebIDE 편집기에서 ~/project/SubsetCheck.java를 엽니다.
main 메서드 외부의 SubsetCheck 클래스 내부에 다음 메서드를 추가합니다.
// Method to manually check if subList is a subset of mainList
public static boolean isSubsetManual(List<String> mainList, List<String> subList) {
// Iterate through each element in the subList
for (String element : subList) {
// If the mainList does NOT contain the current element from subList,
// then subList is not a subset, and we can return false immediately.
if (!mainList.contains(element)) {
return false;
}
}
// If we have checked all elements in subList and found them all in mainList,
// then subList is a subset.
return true;
}
이 새로운 메서드 isSubsetManual은 두 개의 리스트를 입력으로 받습니다. 그런 다음 subList의 각 element를 반복합니다. 루프 내에서 contains() 메서드를 사용하여 mainList가 현재 element를 포함하는지 확인합니다. subList에서 mainList에 없는 요소가 하나라도 발견되면, 즉시 subList가 부분 집합이 아니고 false를 반환합니다. 루프가 subList에서 mainList에 없는 요소를 찾지 않고 완료되면 모든 요소가 존재한다는 의미이며, 메서드는 true를 반환합니다.
이제 main 메서드에서 이 새 메서드를 호출하여 결과를 containsAll()과 비교해 보겠습니다. SubsetCheck.java의 main 메서드를 수정하여 isSubsetManual에 대한 호출을 포함합니다.
import java.util.ArrayList;
import java.util.List;
public class SubsetCheck {
public static void main(String[] args) {
// Create the main list
List<String> mainList = new ArrayList<>();
mainList.add("Apple");
mainList.add("Banana");
mainList.add("Cherry");
mainList.add("Date");
// Create a potential subset list
List<String> subList = new ArrayList<>();
subList.add("Banana");
subList.add("Cherry");
// Check if subList is a subset of mainList using containsAll()
boolean isSubsetContainsAll = mainList.containsAll(subList);
// Check if subList is a subset of mainList using manual loop
boolean isSubsetManualCheck = isSubsetManual(mainList, subList);
// Print the result
System.out.println("Main List: " + mainList);
System.out.println("Sub List: " + subList);
System.out.println("Is subList a subset of mainList (containsAll)? " + isSubsetContainsAll);
System.out.println("Is subList a subset of mainList (manual check)? " + isSubsetManualCheck);
// Create another list that is not a subset
List<String> anotherList = new ArrayList<>();
anotherList.add("Banana");
anotherList.add("Grape"); // Grape is not in mainList
// Check if anotherList is a subset of mainList using containsAll()
boolean isAnotherSubsetContainsAll = mainList.containsAll(anotherList);
// Check if anotherList is a subset of mainList using manual loop
boolean isAnotherSubsetManualCheck = isSubsetManual(mainList, anotherList);
// Print the result for the second check
System.out.println("\nAnother List: " + anotherList);
System.out.println("Is anotherList a subset of mainList (containsAll)? " + isAnotherSubsetContainsAll);
System.out.println("Is anotherList a subset of mainList (manual check)? " + isAnotherSubsetManualCheck);
}
// Method to manually check if subList is a subset of mainList
public static boolean isSubsetManual(List<String> mainList, List<String> subList) {
// Iterate through each element in the subList
for (String element : subList) {
// If the mainList does NOT contain the current element from subList,
// then subList is not a subset, and we can return false immediately.
if (!mainList.contains(element)) {
return false;
}
}
// If we have checked all elements in subList and found them all in mainList,
// then subList is a subset.
return true;
}
}
수정된 SubsetCheck.java 파일을 저장합니다.
이제 터미널에서 업데이트된 코드를 컴파일합니다.
javac SubsetCheck.java
그리고 프로그램을 다시 실행합니다.
java SubsetCheck
containsAll() 메서드와 수동 루프 메서드 모두 동일한 결과를 생성하는 것을 보여주는 다음과 유사한 출력을 볼 수 있습니다.
Main List: [Apple, Banana, Cherry, Date]
Sub List: [Banana, Cherry]
Is subList a subset of mainList (containsAll)? true
Is subList a subset of mainList (manual check)? true
Another List: [Banana, Grape]
Is anotherList a subset of mainList (containsAll)? false
Is anotherList a subset of mainList (manual check)? false
이 단계는 잠재적인 부분 집합을 반복하고 각 요소가 주 리스트에 있는지 확인하여 containsAll()과 동일한 결과를 얻을 수 있음을 보여줍니다. containsAll()은 일반적으로 간결함과 Java 라이브러리에서 잠재적인 성능 최적화로 인해 선호되지만, 수동 접근 방식을 이해하는 것은 학습에 가치가 있습니다.