🛠️ 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 |
|
addAll(Collection c) | Adds all elements from another collection |
|
remove(Object o) | Removes the specified element |
|
removeAll(Collection c) | Removes all elements in the specified collection |
|
contains(Object o) | Returns true if the element exists |
|
containsAll(Collection c) | Returns true if all elements are present |
|
isEmpty() | Checks if the collection is empty |
|
size() | Returns the number of elements |
|
clear() | Removes all elements |
|
iterator() | Returns an iterator to traverse the collection |
|
toArray() | Converts collection to an array |
|
✅ 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
Collectioninterface, which is inherited byList,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>).