JAVA - Zero to Hero / Collection Framework

Common Collection Methods

🛠️ Common Collection Methods in Java

The Collection interface is the root interface for most collection types (List, Set, Queue, etc.). It defines several generic methods that are implemented by all collection classes like ArrayList, HashSet, LinkedList, etc.

These methods are used to add, remove, search, or manipulate the elements in a collection.


✅ Frequently Used Methods

Method

Description

Example

add(E e)

Adds an element to the collection

list.add("Apple");

addAll(Collection c)

Adds all elements from another collection

list.addAll(otherList);

remove(Object o)

Removes the specified element

set.remove("Banana");

removeAll(Collection c)

Removes all elements in the specified collection

set.removeAll(otherSet);

contains(Object o)

Returns true if the element exists

list.contains("Apple");

containsAll(Collection c)

Returns true if all elements are present

set.containsAll(otherSet);

isEmpty()

Checks if the collection is empty

list.isEmpty();

size()

Returns the number of elements

set.size();

clear()

Removes all elements

list.clear();

iterator()

Returns an iterator to traverse the collection

Iterator it = list.iterator();

toArray()

Converts collection to an array

Object[] arr = list.toArray();


✅ Example Program Using Common Methods

import java.util.ArrayList;

public class CollectionMethodsExample {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        System.out.println("Fruits: " + fruits); // [Apple, Banana, Mango]

        fruits.remove("Banana");
        System.out.println("After removal: " + fruits); // [Apple, Mango]

        System.out.println("Contains Mango? " + fruits.contains("Mango")); // true

        System.out.println("Size: " + fruits.size()); // 2

        fruits.clear();
        System.out.println("Is empty? " + fruits.isEmpty()); // true
    }
}
Fruits: [Apple, Banana, Mango]
After removal: [Apple, Mango]
Contains Mango? true
Size: 2
Is empty? true

🧠 Notes:

  • Most of these methods come from the Collection interface, which is inherited by List, Set, Queue, etc.

  • Some classes (like Map) don’t use these directly but have similar method names (put, get, etc.).

  • Generics help ensure type safety in these methods (e.g., ArrayList<String>).