The Collection interface provides support for the implementation of a mathematical bag – an unordered collection of objects that may contain duplicates.
In Java, the Collection
interface is a part of the Java Collections Framework and is present in the java.util
package. It is at the top of the hierarchy of collection interfaces. The Collection
interface represents a group of objects, known as elements. It provides a standard set of methods to manipulate collections, such as adding, removing, and querying elements.
Some common methods provided by the Collection
interface include add
, remove
, contains
, size
, isEmpty
, and iterator
. Implementations of the Collection
interface include classes like ArrayList
, LinkedList
, HashSet
, and others.
Here’s a simple example of using the Collection
interface:
import java.util.Collection;
import java.util.ArrayList;
public class CollectionExample {
public static void main(String[] args) {
// Creating a collection (ArrayList) of integers
Collection<Integer> numbers = new ArrayList<>();
// Adding elements to the collection
numbers.add(1);
numbers.add(2);
numbers.add(3);
// Displaying the elements of the collection
System.out.println("Collection elements: " + numbers);
// Removing an element from the collection
numbers.remove(2);
// Displaying the modified collection
System.out.println("Modified collection: " + numbers);
}
}
In this example, an ArrayList
is used to implement the Collection
interface, and various methods of the Collection
interface are demonstrated.