Wednesday, 11 June 2025

Java Interview Question : JAVA Collection vs. Collections

 

java.util.Collection 

What it is: Collection is an interface that represents the root of the collection hierarchy in the Java Collections Framework. It defines the common behavior for a group of objects, known as its elements.

Purpose: It acts as a blueprint for all concrete collection types (like Lists, Sets, and Queues) that store individual elements. It specifies the basic operations that all collections should support.

import java.util.*;

public class CollectionExample {
    public static void main(String[] args) {
        Collection<String> names = new ArrayList<>(); // ArrayList implements List, which extends Collection
        names.add("Akshay");
        names.add("Ajay");
        names.add("Abhay");

        System.out.println("Collection elements: " + names); // Output: [Akshay, Ajay, Abhay]
       
        names.remove("Akshay");

        System.out.println("After removing Akshay: " + names); // Output: [Ajay, Abhay]

        System.out.println("Size: " + names.size()); // Output: 2
    }
}

java.util.Collections 

What it is: Collections is a utility class that provides static methods that operate on or return collections. It's like a helper class for the Collection interfaces and their implementations.

Purpose: It offers various polymorphic algorithms and utility methods that can be applied to Collection objects (or their sub-interfaces like List and Set). These methods include sorting, searching, shuffling, reversing, and creating thread-safe or unmodifiable versions of collections.

import java.util.*;

public class CollectionsExample {
    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<>();

        numbers.add(5);
        numbers.add(2);
        numbers.add(8);
        numbers.add(1);

        System.out.println("Original List: " + numbers); // Output: [5, 2, 8, 1]

        // Using Collections.sort()
        Collections.sort(numbers);
        System.out.println("Sorted List: " + numbers); // Output: [1, 2, 5, 8]

        // Using Collections.reverse()
        Collections.reverse(numbers);
        System.out.println("Reversed List: " + numbers); // Output: [8, 5, 2, 1]

        // Using Collections.max()
        System.out.println("Maximum element: " + Collections.max(numbers)); // Output: 8

        // Creating an unmodifiable list
        List<String> immutableList = Collections.unmodifiableList(List.of("apple", "banana"));

        // immutableList.add("orange"); // This would throw UnsupportedOperationException
        System.out.println("Immutable List: " + immutableList); // Output: [apple, banana]
    }
}

No comments:

Post a Comment