Skip to content

The Collections interface

In Java, the Collections Framework provides a set of classes and interfaces that implement various types of collections. The framework includes classes that allow you to store and manipulate groups of objects, such as lists, sets, and maps. The Collection interface is the root interface of the Java Collections Framework, and it defines the basic operations that are common to all collections.

1. The Collection Interface

The Collection interface is a part of the java.util package and is the root interface for most of the collections in Java. It represents a group of objects, known as elements, and provides methods for basic operations like adding, removing, and querying elements. However, it is important to note that the Collection interface itself does not represent a specific collection type (like a list or set); it is a supertype for more specific collection interfaces such as List, Set, and Queue.

Key Methods in the Collection Interface:

  • add(E e): Adds the specified element to the collection.

    java
    collection.add(element);
  • remove(Object o): Removes a single instance of the specified element from the collection.

    java
    collection.remove(element);
  • clear(): Removes all elements from the collection.

    java
    collection.clear();
  • size(): Returns the number of elements in the collection.

    java
    int size = collection.size();
  • isEmpty(): Returns true if the collection contains no elements.

    java
    boolean isEmpty = collection.isEmpty();
  • contains(Object o): Returns true if the collection contains the specified element.

    java
    boolean contains = collection.contains(element);
  • iterator(): Returns an iterator over the elements in the collection.

    java
    Iterator<E> iterator = collection.iterator();
  • toArray(): Returns an array containing all elements in the collection.

    java
    Object[] array = collection.toArray();

2. Subinterfaces of Collection

The Collection interface has several important subinterfaces in the Java Collections Framework:

List Interface

  • A List is an ordered collection that allows duplicate elements. It represents a sequence of elements, where each element can be accessed by its position in the list (index-based access).

Common Implementations:

  • ArrayList
  • LinkedList
  • Vector

Example:

java
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

for (String fruit : list) {
    System.out.println(fruit);
}

Set Interface

  • A Set is a collection that does not allow duplicate elements. It models the mathematical set abstraction and does not maintain the order of elements.

Common Implementations:

  • HashSet
  • LinkedHashSet
  • TreeSet

Example:

java
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple");  // Duplicate, will not be added

for (String fruit : set) {
    System.out.println(fruit);  // "Apple" and "Banana" (no duplicates)
}

Queue Interface

  • A Queue is a collection designed for holding elements prior to processing. It typically follows the First-In-First-Out (FIFO) principle.

Common Implementations:

  • LinkedList
  • PriorityQueue
  • ArrayDeque

Example:

java
Queue<String> queue = new LinkedList<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Orange");

System.out.println(queue.poll());  // Apple (removed first element)

Deque Interface

  • A Deque (Double-Ended Queue) is a queue that allows adding and removing elements from both ends.

Common Implementations:

  • ArrayDeque
  • LinkedList

Example:

java
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("Apple");
deque.addLast("Banana");

System.out.println(deque.removeFirst());  // Apple
System.out.println(deque.removeLast());   // Banana

SortedSet Interface (Subinterface of Set)

  • A SortedSet is a set that maintains its elements in a sorted order. It extends the Set interface and guarantees that elements will be sorted according to their natural ordering or by a comparator.

Common Implementation:

  • TreeSet

Example:

java
SortedSet<String> sortedSet = new TreeSet<>();
sortedSet.add("Banana");
sortedSet.add("Apple");
sortedSet.add("Orange");

for (String fruit : sortedSet) {
    System.out.println(fruit);  // Will print elements in sorted order: Apple, Banana, Orange
}
  • The Map interface represents a collection of key-value pairs. A Map does not extend Collection, but it is an essential part of the Collections Framework. The map allows keys to be mapped to values.

Common Implementations:

  • HashMap
  • TreeMap
  • LinkedHashMap

Example:

java
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Orange");

System.out.println(map.get(1));  // Output: Apple

3. Common Operations on Collections

Here are some examples of common operations across different collection types in Java:

Adding Elements:

java
Collection<String> collection = new ArrayList<>();
collection.add("Element1");
collection.add("Element2");

Removing Elements:

java
collection.remove("Element1");  // Removes Element1

Iterating Over Collections:

  • Using an iterator:

    java
    Iterator<String> iterator = collection.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
  • Using a for-each loop:

    java
    for (String element : collection) {
        System.out.println(element);
    }

Checking if an Element Exists:

java
boolean exists = collection.contains("Element2");

Getting the Size:

java
int size = collection.size();

Clearing the Collection:

java
collection.clear();

4. Examples of Collection Implementations

  • ArrayList (a List implementation):

    java
    List<String> list = new ArrayList<>();
    list.add("Apple");
    list.add("Banana");
    list.add("Orange");
  • HashSet (a Set implementation):

    java
    Set<String> set = new HashSet<>();
    set.add("Apple");
    set.add("Banana");
    set.add("Apple");  // Duplicate won't be added
  • PriorityQueue (a Queue implementation):

    java
    Queue<String> queue = new PriorityQueue<>();
    queue.add("Apple");
    queue.add("Banana");
    queue.add("Orange");
  • TreeMap (a Map implementation):

    java
    Map<Integer, String> map = new TreeMap<>();
    map.put(1, "Apple");
    map.put(2, "Banana");

5. Conclusion

The Collection interface and its subinterfaces (List, Set, Queue, etc.) provide a powerful set of data structures to store, retrieve, and manipulate groups of objects. By understanding the common methods and the different types of collections, you can select the appropriate collection for your needs. Java Collections Framework is highly efficient, flexible, and widely used in real-world applications.

J2J Institute private limited