Java 实例 - 集合长度


以下实例演示了如何使用 Collections 类 的collection.add() 来添加数据并使用 collection.size()来计算集合的长度:

  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. size = collection.size();
  27. if (collection.isEmpty()){
  28. System.out.println("集合是空的");
  29. }
  30. else{
  31. System.out.println( "集合长度: " + size);
  32. }
  33. System.out.println();
  34. }
  35. }

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

  1. 集合实例!
  2.  
  3. 集合数据: White Yellow Blue Green
  4. 集合长度: 4
  5.