Collection Interface
The Collection Interface is the root interface of the Java Collections Framework. It represents a group of objects, known as elements. The Collection
interface provides fundamental methods to work with elements, such as adding, removing, and querying elements in a collection. All other collection interfaces (Set
, List
, Queue
, etc.) extend this interface.
Key Methods in Collection Interface
add(E e):
- Adds the specified element to the collection. Returns
true
if the element was successfully added.
collection.add("Alice");
- Adds the specified element to the collection. Returns
remove(Object o):
- Removes the specified element from the collection. Returns
true
if the element was found and removed.
collection.remove("Alice");
- Removes the specified element from the collection. Returns
size():
- Returns the number of elements in the collection.
int size = collection.size();
isEmpty():
- Checks if the collection is empty. Returns
true
if the collection contains no elements.
boolean empty = collection.isEmpty();
- Checks if the collection is empty. Returns
contains(Object o):
- Checks if the collection contains the specified element.
boolean hasAlice = collection.contains("Alice");
clear():
- Removes all elements from the collection.
collection.clear();
iterator():
- Returns an iterator that can be used to traverse the elements of the collection.
Iterator<E> iterator = collection.iterator();
Example: Using Collection Interface
import java.util.*;
public class CollectionInterfaceExample {
public static void main(String[] args) {
// Creating a Collection (List implementation)
Collection<String> names = new ArrayList<>();
// Adding elements
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Iterating through the collection
for (String name : names) {
System.out.println(name);
}
// Removing an element
names.remove("Bob");
// Checking if an element is present
boolean hasAlice = names.contains("Alice");
System.out.println("Contains Alice: " + hasAlice);
// Size of collection
System.out.println("Size: " + names.size());
// Clearing the collection
names.clear();
}
}