Home  >  Article  >  Java  >  Java Example - Collection Length

Java Example - Collection Length

黄舟
黄舟Original
2017-01-21 11:02:501722browse

The following example demonstrates how to use collection.add() of the Collections class to add data and use collection.size() to calculate the length of the collection:

/*
 author by w3cschool.cc
 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();
      size = collection.size();
      if (collection.isEmpty()){
         System.out.println("集合是空的");
      }
      else{
         System.out.println( "集合长度: " + size);
      }
      System.out.println();
   }}

The output of the above code is:

集合实例!
集合数据: White Yellow Blue Green 
集合长度: 4

The above is the Java example - collection length content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn