Java-Beispiele - Ein bestimmtes Element aus einer Sammlung entfernen
Das folgende Beispiel zeigt, wie die Methode collection.remove() der Collection-Klasse verwendet wird, um das angegebene Element aus einer Collection zu entfernen:
Main.java-Datei
import java.util.*;
public class Main {
public static void main(String [] args) {
System.out.println( "Collection-Beispiel!\n" );
int size;
HashSet collection = new HashSet ();
String str1 = "Gelb", str2 = "Weiß", str3 =
"Grün", str4 = "Blau";
Iterator iterator;
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("Sammlungsdaten:");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
collection.remove(str2);
System.out.println("Nach dem Löschen [" + str2 + "]\n");
System.out.print("Jetzt sind die Sammlungsdaten:");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
System.out.println("Sammlungsgröße:" + size + "\n");
}
}
Die Ausgabe beim Ausführen des obigen Codes ist:
集合实例! 集合数据: White Yellow Blue Green 删除之后 [White] 现在集合的数据是: Yellow Blue Green 集合大小: 3Andere Erweiterungen
Java-Beispiele