The java.util.Collection
interface is a core interface in the Java Collection Framework that represents a group of objects, known as elements. It is used to store, retrieve, and manipulate a collection of elements in a single unit.
The Collection
interface extends the Iterable
interface, which means that it can be used with the for-each loop to iterate over its elements. It also defines a number of methods for adding, removing, and checking the presence of elements, as well as methods for performing bulk operations on the elements of the collection.
Here is an example of how to use the Collection
interface in Java:
import java.util.ArrayList; import java.util.Collection; public class Main { public static void main(String[] args) { Collection<String> collection = new ArrayList<>(); // Add elements to the collection collection.add("apple"); collection.add("banana"); collection.add("cherry"); // Check the size of the collection System.out.println("Size: " + collection.size()); // Check if the collection contains a specific element System.out.println("Contains cherry: " + collection.contains("cherry")); // Remove an element from the collection collection.remove("cherry"); // Iterate over the elements of the collection for (String element : collection) { System.out.println(element); } } }Source:www.lautturi.com
In this example, an ArrayList
implementation of the Collection
interface is used to store a list of strings. The add
and remove
methods are used to add and remove elements from the collection, and the size
and contains
methods are used to check the size and presence of elements in the collection. The for-each loop is used to iterate over the elements of the collection and print them to the console.