Java Collection Interface
In Java, the Collection
interface is a member of the java.util
package and defines a group of objects known as a collection. A collection represents a group of objects, known as its elements, which are stored in a particular order and can be manipulated as a single unit.
The Collection
interface is an interface and does not have any implementation class. It is used as the superinterface for several subinterfaces and concrete classes, such as List
, Set
, and Queue
.
The Collection
interface provides several methods that can be used to manipulate its elements, including methods for adding, removing, and searching for elements, as well as methods for determining the size of the collection and its characteristics.
Here is an example of how to use the Collection
interface:
import java.util.ArrayList;
import java.util.Collection;
public class Main {
public static void main(String[] args) {
// Create a collection
Collection<String> collection = new ArrayList<>();
// Add elements to the collection
collection.add("A");
collection.add("B");
collection.add("C");
// Remove an element from the collection
collection.remove("B");
// Check if the collection contains a specific element
boolean containsA = collection.contains("A"); // returns true
boolean containsB = collection.contains("B"); // returns false
// Get the size of the collection
int size = collection.size(); // returns 2
// Check if the collection is empty
boolean isEmpty = collection.isEmpty(); // returns false
}
}
In this example, we create a collection of strings using an ArrayList
and add elements to the collection using the add()
method. We then remove an element from the collection using the remove()
method and use the contains()
method to check if the collection contains a specific element. We also use the size()
and isEmpty()
methods to get the size of the collection and check if it is empty.
The Collection
interface is a powerful and flexible interface that allows you to manipulate and work with groups of objects in a variety of ways. It is an essential part of the Java Collections Framework and is used in a wide range of applications.