Java Example - Collection Size
\n \nThe following example demonstrates how to use the Collections class's collection.add() to add data and collection.size() to calculate the size of the collection:
Main.java File
\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n System.out.println("Collection Instance!n");\n int size;\n HashSet collection = new HashSet();\n String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";\n Iterator iterator;\n collection.add(str1);\n collection.add(str2);\n collection.add(str3);\n collection.add(str4);\n System.out.print("Collection Data: ");\n iterator = collection.iterator();\n while (iterator.hasNext()) {\n System.out.print(iterator.next() + "");\n }\n System.out.println();\n size = collection.size();\n if (collection.isEmpty()) {\n System.out.println("Collection is Empty");\n } else {\n System.out.println("Collection Length: " + size);\n }\n System.out.println();\n }\n}\n\n The output of the above code is:
\nCollection Instance!\nCollection Data: White Yellow Blue Green\nCollection Length: 4\n\n
YouTip