The Collection Interface in Java is the root interface(a kind of abstract class) in java.util package. It represents a group of objects, known as elements, and provides a unified way to manipulate and work with collections of data.
Key Points About the Collection Interface
Root Interface: The Collection interface is the root interface of all Collection objects in Java, except Map.
Generic Interface: A generic interface, meaning it can work with any type of object (_e.g.,_ Collection<String>, Collection etc.).
Common Methods: For example, we can use the following methods for both adding and deleting elements to an array: add(), remove (), size().
Extends Iterable: The Collectioneuml; interface extends the Iterableinterface, and this means that all collections can be iterated over via either an iterator or the enhanced for-loop construct.
- public interface Collection<E>
- extends Iterable<E>
Methods in Collection Interface:
1.public Boolean add(Object obj)
- Used to add element in to the collection
2.public Boolean addAll(Collection c)
- Adds all the elements of c to the invoking collection. Returns true if the operation succeeded else returns false.
3.public boolean isEmpty()
- Returns true if collection is empty otherwise returns false.
4.public boolean remove(Object obj)
- Remove element from collection. Returns true if successful deletion.
5.public boolean removeAll(Collection c)
- Removes all elements of a collection.
6.public void clear()
- Deletes total elements from collection
7.public boolean contains(Object obj)
- This method used to search an element
8.public boolean containsAll(Collection c)
- This method used to search an element in a collection
9.public boolean retianAll(Collection c)
- Used to delete all elements from a collection except specified one.
10.public int size()
- Returns total numbers of elements in a collection
11.public Iterator iterator()
- Returns iterator for the collection
12.public boolean equals(Object obj)
13.public int hashCode()
14.public Object[] toArray()
- This method used to convert collection into array
15.public Object[] toArray(Object[] obj)
- Returns an array containing only those collection elements whose type matches that of array.
Difference Between Collection and Collections:
- Collection is the base interface for most of the classes.
- Collections is the utility class.