The Collection interface in Java defines a set of methods that provide common operations for storing and manipulating a group of objects. These methods allow you to add, remove, search, and iterate over elements within a collection.
Here's a breakdown of the methods defined in the Collection interface:
Core Methods:
add(E e)
: Adds the specified element to the collection.addAll(Collection<? extends E> c)
: Adds all elements from the specified collection to this collection.clear()
: Removes all elements from the collection.contains(Object o)
: Checks if the collection contains the specified element.containsAll(Collection<?> c)
: Checks if the collection contains all elements from the specified collection.isEmpty()
: Checks if the collection is empty.iterator()
: Returns an iterator over the elements in the collection.remove(Object o)
: Removes the specified element from the collection.removeAll(Collection<?> c)
: Removes all elements from the collection that are contained in the specified collection.retainAll(Collection<?> c)
: Retains only the elements in the collection that are also contained in the specified collection.size()
: Returns the number of elements in the collection.toArray()
: Returns an array containing all elements in the collection.toArray(T[] a)
: Returns an array containing all elements in the collection, using the specified array if possible.
Example:
import java.util.ArrayList;
import java.util.Collection;
public class CollectionExample {
public static void main(String[] args) {
Collection<String> names = new ArrayList<>();
// Adding elements
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Checking size
System.out.println("Number of names: " + names.size()); // Output: 3
// Checking if contains an element
System.out.println("Contains Bob? " + names.contains("Bob")); // Output: true
// Removing an element
names.remove("Bob");
// Iterating over elements
for (String name : names) {
System.out.println(name); // Output: Alice, Charlie
}
}
}
These methods provide a foundation for working with collections in Java, allowing you to perform various operations efficiently.