Java サンプル - コレクション内の指定要素を削除
以下の例では、Collection クラスの collection.remove() メソッドを使用して、コレクション内の指定された要素を削除する方法を示しています:
Main.java ファイル
import java.util.*;
public class Main {
public static void main(String [] args) {
System.out.println( "コレクションの例!\n" );
int size;
HashSet collection = new HashSet ();
String str1 = "Yellow", str2 = "White", str3 =
"Green", str4 = "Blue";
Iterator iterator;
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("コレクションデータ:");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
collection.remove(str2);
System.out.println("削除後 [" + str2 + "]\n");
System.out.print("現在のコレクションデータ:");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
System.out.println("コレクションのサイズ:" + size + "\n");
}
}
上記のコードを実行した場合の出力結果は次のとおりです:
集合实例! 集合数据: White Yellow Blue Green 删除之后 [White] 现在集合的数据是: Yellow Blue Green 集合大小: 3その他の拡張
Java サンプル