Vérification avec une boucle manuelle
Dans l'étape précédente, nous avons utilisé la pratique méthode containsAll()
pour vérifier si une liste est un sous-ensemble d'une autre. Bien que containsAll()
soit efficace, il est utile de comprendre comment effectuer cette vérification manuellement en utilisant une boucle. Cela approfondira votre compréhension du fonctionnement interne des méthodes de collection.
Ajoutons une nouvelle méthode à notre fichier SubsetCheck.java
pour effectuer la vérification de sous-ensemble manuellement. Ouvrez ~/project/SubsetCheck.java
dans l'éditeur de l'WebIDE.
Ajoutez la méthode suivante à l'intérieur de la classe SubsetCheck
, mais en dehors de la méthode main
:
// 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;
}
Cette nouvelle méthode isSubsetManual
prend deux listes en entrée. Elle parcourt ensuite chaque élément
de la subList
. À l'intérieur de la boucle, elle vérifie si la mainList
contient l'élément
actuel en utilisant la méthode contains()
. Si elle trouve même un seul élément de la subList
qui n'est pas dans la mainList
, elle sait immédiatement que la subList
n'est pas un sous-ensemble et retourne false
. Si la boucle se termine sans trouver d'élément de la subList
manquant dans la mainList
, cela signifie que tous les éléments sont présents, et la méthode retourne true
.
Maintenant, appelons cette nouvelle méthode depuis notre méthode main
pour comparer son résultat avec celui de containsAll()
. Modifiez la méthode main
dans SubsetCheck.java
pour inclure des appels à 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;
}
}
Enregistrez le fichier SubsetCheck.java
modifié.
Maintenant, compilez le code mis à jour dans le Terminal :
javac SubsetCheck.java
Et exécutez le programme à nouveau :
java SubsetCheck
Vous devriez voir une sortie similaire à ceci, montrant que la méthode containsAll()
et notre méthode de boucle manuelle produisent les mêmes résultats :
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
Cette étape démontre que vous pouvez obtenir le même résultat que containsAll()
en parcourant le potentiel sous-ensemble et en vérifiant la présence de chaque élément dans la liste principale. Bien que containsAll()
soit généralement préféré pour sa concision et ses optimisations de performance potentielles dans la bibliothèque Java, comprendre l'approche manuelle est précieux pour l'apprentissage.