Java サンプル - コレクションの長さ

Java 实例Java サンプル

以下の例では、Collections クラスの collection.add() を使用してデータを追加し、 collection.size() を使用してコレクションの長さを計算する方法を示しています。

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 实例Java サンプル

その他の拡張