DEV Community

vinoth kumar
vinoth kumar

Posted on

Difference between Collection and Collections in Java

  • *Collection *(Interface): This is a root-level interface of the Java Collections Framework (JCF). It represents a group of objects, known as elements. Collection provides general-purpose methods that all collections share, such as adding, removing, and checking elements.

  • *Collections *(Class): This is a utility class that consists of static methods that operate on or return collections. It contains methods for algorithms like sorting, searching, and manipulating collections.

1. Collection (Interface)
Let’s use a simple example of a List, which implements the Collection interface.

import java.util.*;

public class CollectionExample {
    public static void main(String[] args) {
        // Creating a List, which is a subtype of Collection
        Collection<String> list = new ArrayList<>();

        // Adding elements
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // Displaying the list
        System.out.println("List elements: " + list);

        // Removing an element
        list.remove("Banana");

        // Checking if an element exists
        System.out.println("Does list contain 'Apple'? " + list.contains("Apple"));

        // Displaying the size of the list
        System.out.println("Size of list: " + list.size());
    }
}
Enter fullscreen mode Exit fullscreen mode

Output for the Collection Interface Example:


List elements: [Apple, Banana, Orange]
Does list contain 'Apple'? true
Size of list: 2
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Initially, the list contains “Apple”, “Banana”, and “Orange”.
  • After removing “Banana”, the list only has two elements.
  • The method list.contains("Apple") returns true because "Apple" is still in the list.
  • The size of the list is displayed as 2 after the removal of one element.

2. Collections (Class)
Now, let’s use the Collections class to sort the list.

import java.util.*;

public class CollectionsExample {
    public static void main(String[] args) {
        // Creating a List
        List<String> list = new ArrayList<>();

        // Adding elements
        list.add("Banana");
        list.add("Apple");
        list.add("Orange");

        // Sorting the list using Collections.sort()
        Collections.sort(list);

        // Displaying the sorted list
        System.out.println("Sorted list: " + list);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output for the Collections Class Example:


Sorted list: [Apple, Banana, Orange]
Enter fullscreen mode Exit fullscreen mode

Explanation:

The Collections.sort() method sorts the list in alphabetical order. The original order of insertion was [Banana, Apple, Orange], and after sorting, the elements appear as [Apple, Banana, Orange].

Top comments (0)