>  기사  >  Java  >  Java 예제 - 컬렉션 길이

Java 예제 - 컬렉션 길이

黄舟
黄舟원래의
2017-01-21 11:02:501661검색

다음 예에서는 Collections 클래스의 collection.add()를 사용하여 데이터를 추가하고 collection.size()를 사용하여 컬렉션 길이를 계산하는 방법을 보여줍니다.

/*
 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();
   }}

의 출력 위 코드는

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

위는 Java 예시 - 컬렉션 길이입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.