Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
The Collection
interface in Java is the root interface for all collection classes (excluding maps). It provides a unified way to work with groups of objects, such as lists, sets, and queues. The Collection
interface is part of the Java Collections Framework and is defined in the java.util
package.
In this tutorial, we'll cover the basic concepts and methods of the Collection
interface.
The Collection
interface provides methods for performing common operations on collections, such as adding and removing elements, querying the size of the collection, and checking whether an element is present. It also includes methods for iterating through the elements in a collection.
Here's a list of some key methods in the Collection
interface:
boolean add(E e)
: Adds an element to the collection.boolean remove(Object o)
: Removes a single instance of the specified element from the collection.int size()
: Returns the number of elements in the collection.boolean isEmpty()
: Returns true if the collection contains no elements.boolean contains(Object o)
: Returns true if the collection contains the specified element.Iterator<E> iterator()
: Returns an iterator over the elements in the collection.Object[] toArray()
: Returns an array containing all the elements in the collection.The Collection
interface itself cannot be instantiated directly, as it's an interface. Instead, you'll typically work with one of its subinterfaces or implementing classes, such as ArrayList
, HashSet
, or LinkedList
.
Example:
import java.util.ArrayList; import java.util.Collection; public class Main { public static void main(String[] args) { // Create a collection using an ArrayList Collection<String> names = new ArrayList<>(); // Add elements to the collection names.add("Alice"); names.add("Bob"); names.add("Carol"); // Check if the collection contains an element System.out.println("Contains 'Alice': " + names.contains("Alice")); // Output: Contains 'Alice': true // Iterate through the elements in the collection for (String name : names) { System.out.println(name); } // Remove an element from the collection names.remove("Bob"); // Get the size of the collection System.out.println("Size: " + names.size()); // Output: Size: 2 } }
In this example, we create a collection using an ArrayList
and perform various operations like adding elements, checking if an element is present, iterating through elements, removing an element, and getting the size of the collection.
To create a custom collection, you can implement the Collection
interface directly or extend one of the existing classes or interfaces that implement it.
Example of a custom collection implementing the Collection
interface:
import java.util.AbstractCollection; import java.util.Iterator; public class CustomCollection<E> extends AbstractCollection<E> { // Your custom implementation details here @Override public Iterator<E> iterator() { // Return an iterator for your custom collection return null; } @Override public int size() { // Return the size of your custom collection return 0; } }
In this example, we create a custom collection by extending the AbstractCollection
class, which is a skeletal implementation of the Collection
interface. We need to provide implementations for the iterator()
and size()
methods.
In summary, the Collection
interface in Java provides a unified way to work with groups of objects. It includes methods for performing common operations on collections
Implementing the Collection Interface in Java:
The Collection
interface is the root interface in the Java Collection Framework. Implementing it allows custom classes to represent a group of objects.
import java.util.Collection; import java.util.ArrayList; public class CustomCollection implements Collection<String> { private ArrayList<String> elements = new ArrayList<>(); @Override public int size() { return elements.size(); } @Override public boolean isEmpty() { return elements.isEmpty(); } // Implement other methods }
Java Collection Framework Hierarchy:
The Java Collection framework includes interfaces like Collection
, List
, Set
, Map
, and classes like ArrayList
, LinkedList
, HashSet
, etc.
Java Collection Interface vs. List Interface:
The Collection
interface is a more general interface, while the List
interface extends Collection
and allows duplicate elements with an ordered index.
import java.util.Collection; import java.util.List; import java.util.ArrayList; public class ListExample implements List<String> { private ArrayList<String> elements = new ArrayList<>(); // Implement List methods }
Set Interface in Java Collection Framework:
The Set
interface represents an unordered collection of unique elements.
import java.util.Set; import java.util.HashSet; public class SetExample { public static void main(String[] args) { Set<String> uniqueElements = new HashSet<>(); // Implement Set operations } }
Map Interface and Its Role in Java Collections:
The Map
interface represents a collection of key-value pairs. It doesn't extend the Collection
interface.
import java.util.Map; import java.util.HashMap; public class MapExample { public static void main(String[] args) { Map<String, Integer> ages = new HashMap<>(); // Implement Map operations } }
Iterating Through Elements in Java Collection Interface:
Use an iterator or enhanced for loop to iterate through elements in a Collection
.
import java.util.Collection; import java.util.ArrayList; import java.util.Iterator; public class IterationExample { public static void main(String[] args) { Collection<String> colors = new ArrayList<>(); // Add elements to colors // Using Iterator Iterator<String> iterator = colors.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // Using enhanced for loop for (String color : colors) { System.out.println(color); } } }
Adding and Removing Elements in Java Collection Interface:
Use the add
and remove
methods to add and remove elements from a Collection
.
import java.util.Collection; import java.util.ArrayList; public class AddRemoveExample { public static void main(String[] args) { Collection<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.remove("Apple"); } }
Custom Implementations of Java Collection Interface: Creating custom implementations allows you to tailor collections to specific needs.
import java.util.Collection; import java.util.Iterator; public class CustomCollection<T> implements Collection<T> { // Implement Collection methods based on your requirements @Override public Iterator<T> iterator() { // Implement iterator return null; } // Implement other methods }