Home > Java > javaTutorial > Java Example - Collection Length

Java Example - Collection Length

黄舟
Release: 2017-01-21 11:02:50
Original
1745 people have browsed it

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();
   }}
Copy after login

The output of the above code is:

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

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template