YouTip LogoYouTip

Collection Size

Java Example - Collection Size

\n

Java Examples Java Examples

\n

The 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:

\n\n

Main.java File

\n
import 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:

\n
Collection Instance!\nCollection Data: White Yellow Blue Green\nCollection Length: 4
\n\n

Java Examples Java Examples

← Thread InterruptCollection Iterator β†’