Collection Interface

📦 What is the Collection Interface?

The Collection interface is the root interface in the Java Collections Framework. It defines the common behaviors (like adding, removing, and iterating) for all types of collections such as lists, sets, and queues.

It is part of java.util package.


✅ Key Methods in Collection Interface:

Method Description
add(E e) Adds an element to the collection
remove(Object o) Removes the specified element
size() Returns the number of elements
isEmpty() Checks if collection is empty
contains(Object o) Checks if element is present
clear() Removes all elements
iterator() Returns an iterator to loop through items

🧱 Subinterfaces of Collection:

Interface Description Common Implementations
List Ordered, allows duplicates ArrayList, LinkedList
Set No duplicates allowed HashSet, LinkedHashSet
Queue Ordered for processing (FIFO) PriorityQueue, LinkedList

 

⚠️ Map is not a subtype of Collection, though it's part of the Java Collections Framework.


🔍 Example Usage:

import java.util.*;

public class Demo {
    public static void main(String[] args) {
        Collection<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}


📌 Summary:

  • Collection is a base interface for storing a group of objects.
  • It provides core methods shared by all collections.
  • Used as a polymorphic reference type in many real-world Java apps.
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.