Java 实例 - 删除集合中指定元素


以下实例演示了如何使用 Collection 类的 collection.remove() 方法来删除集合中的指定的元素:

  1. /*
  2. author by shouce.ren
  3. Main.java
  4. */
  5.  
  6. import java.util.*;
  7.  
  8. public class Main {
  9. public static void main(String [] args) {
  10. System.out.println( "集合实例!\n" );
  11. int size;
  12. HashSet collection = new HashSet ();
  13. String str1 = "Yellow", str2 = "White", str3 =
  14. "Green", str4 = "Blue";
  15. Iterator iterator;
  16. collection.add(str1);
  17. collection.add(str2);
  18. collection.add(str3);
  19. collection.add(str4);
  20. System.out.print("集合数据: ");
  21. iterator = collection.iterator();
  22. while (iterator.hasNext()){
  23. System.out.print(iterator.next() + " ");
  24. }
  25. System.out.println();
  26. collection.remove(str2);
  27. System.out.println("删除之后 [" + str2 + "]\n");
  28. System.out.print("现在集合的数据是: ");
  29. iterator = collection.iterator();
  30. while (iterator.hasNext()){
  31. System.out.print(iterator.next() + " ");
  32. }
  33. System.out.println();
  34. size = collection.size();
  35. System.out.println("集合大小: " + size + "\n");
  36. }
  37. }

以上代码运行输出结果为:

  1. 集合实例!
  2.  
  3. 集合数据: White Yellow Blue Green
  4. 删除之后 [White]
  5.  
  6. 现在集合的数据是: Yellow Blue Green
  7. 集合大小: 3