Java Collection Interface

The Collection interface is the foundation of the Java Collections Framework. It is an interface that represents a group of objects, or a collection. The Collection interface is extended by several other interfaces such as List, Set, and Queue, which provide additional functionality for working with specific types of collections.

Here are some of the key methods defined in the Collection interface:

  • boolean add(E element): Adds the specified element to the collection.

  • boolean addAll(Collection<? extends E> collection): Adds all elements from the specified collection to the collection.

  • void clear(): Removes all elements from the collection.

  • boolean contains(Object element): Returns true if the collection contains the specified element.

  • boolean containsAll(Collection<?> collection): Returns true if the collection contains all elements from the specified collection.

  • boolean isEmpty(): Returns true if the collection is empty.

  • Iterator<E> iterator(): Returns an iterator over the elements in the collection.

  • boolean remove(Object element): Removes the specified element from the collection.

  • boolean removeAll(Collection<?> collection): Removes all elements from the collection that are also in the specified collection.

  • boolean retainAll(Collection<?> collection): Removes all elements from the collection that are not in the specified collection.

  • int size(): Returns the number of elements in the collection.

  • Object[] toArray(): Returns an array containing all elements in the collection.

  • <T> T[] toArray(T[] array): Returns an array containing all elements in the collection, using the specified array if it is large enough, or creating a new array of the same type if necessary.

Implementations of the Collection interface provide different ways to store and organize collections of objects. For example, the ArrayList class provides a resizable array that can be used to store elements, while the HashSet class provides a hash table that can be used to store unique elements. By using the methods defined in the Collection interface, you can easily manipulate collections of objects and perform common operations such as searching, sorting, and filtering.