Java-Beispiele - Collection-Länge

Java 实例Java-Beispiele

Das folgende Beispiel zeigt, wie man die Methode collection.add() der Klasse Collections verwendet, um Daten hinzuzufügen, und collection.size() verwendet, um die Länge der Collection zu berechnen:

Main.java-Datei

import java.util.*; public class Main { public static void main(String [] args) { System.out.println( "Collection-Instanz!\n" ); int size; HashSet collection = new HashSet (); String str1 = "Gelb", str2 = "Weiß", str3 = "Grün", str4 = "Blau"; Iterator iterator; collection.add(str1); collection.add(str2); collection.add(str3); collection.add(str4); System.out.print("Sammlungsdaten:"); iterator = collection.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); size = collection.size(); if (collection.isEmpty()){ System.out.println("Die Collection ist leer"); } else{ System.out.println( "Collection-Länge:" + size); } System.out.println(); } }

Die Ausgabe beim Ausführen des obigen Codes ist:

集合实例!

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

Java 实例Java-Beispiele

Andere Erweiterungen