Skip to main content

1

Java Collection Interface Methods and Usage

1. Overview​

The Collection interface is the root interface of the Java Collections Framework. It provides several useful methods that can be used by all the collections that implement this interface.

2. Methods of the Collection Interface​

MethodDescription
add(Object o)Adds an object to the collection.
addAll(Collection c)Adds all elements from the given collection to this collection.
clear()Removes all elements from this collection.
contains(Object o)Returns true if the collection contains the specified element.
containsAll(Collection c)Returns true if the collection contains all elements in the given collection.
equals(Object o)Compares the specified object with this collection for equality.
hashCode()Returns the hash code value for this collection.
isEmpty()Returns true if this collection contains no elements.
iterator()Returns an iterator over the elements in this collection.
parallelStream()Returns a parallel Stream with this collection as its source.
remove(Object o)Removes the given object from the collection. If duplicates exist, it removes only the first occurrence.
removeAll(Collection c)Removes all elements present in the given collection from this collection.
removeIf(Predicate filter)Removes all elements that satisfy the given predicate.
retainAll(Collection c)Retains only elements present in the specified collection.
size()Returns the number of elements in the collection.
spliterator()Creates a Spliterator over the elements in this collection.
stream()Returns a sequential Stream with this collection as its source.
toArray()Returns an array containing all elements in this collection.

3. Examples and Usage​

1. Using add(), addAll(), and clear()​

import java.util.ArrayList;
import java.util.List;

public class CollectionExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println("List: " + list);

List<String> moreFruits = new ArrayList<>();
moreFruits.add("Cherry");
moreFruits.add("Dates");
list.addAll(moreFruits);
System.out.println("After addAll: " + list);

list.clear();
System.out.println("After clear: " + list);
}
}
Output:​
List: [Apple, Banana]
After addAll: [Apple, Banana, Cherry, Dates]
After clear: []

2. Using contains(), containsAll(), and isEmpty()​

import java.util.HashSet;
import java.util.Set;

public class ContainsExample {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

System.out.println("Contains 20? " + numbers.contains(20));
System.out.println("Contains 40? " + numbers.contains(40));

Set<Integer> subset = new HashSet<>();
subset.add(10);
subset.add(20);
System.out.println("Contains all [10, 20]? " + numbers.containsAll(subset));

numbers.clear();
System.out.println("Is empty? " + numbers.isEmpty());
}
}
Output:​
Contains 20? true
Contains 40? false
Contains all [10, 20]? true
Is empty? true

3. Using remove(), removeAll(), and removeIf()​

import java.util.ArrayList;
import java.util.List;

public class RemoveExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(20);

numbers.remove(Integer.valueOf(20)); // Removes first occurrence
System.out.println("After remove(20): " + numbers);

List<Integer> removeList = new ArrayList<>();
removeList.add(10);
numbers.removeAll(removeList);
System.out.println("After removeAll([10]): " + numbers);

numbers.removeIf(n -> n > 15);
System.out.println("After removeIf(n > 15): " + numbers);
}
}
Output:​
After remove(20): [10, 30, 20]
After removeAll([10]): [30, 20]
After removeIf(n > 15): []

4. Interfaces Extending the Collection Interface​

Several interfaces extend the Collection interface, adding more functionalities:

InterfaceDescription
ListOrdered collection allowing duplicate elements. Implementations: ArrayList, LinkedList.
SetUnordered collection with unique elements. Implementations: HashSet, TreeSet.
QueueFollows FIFO (First-In-First-Out) principle. Implementations: PriorityQueue, LinkedList.
DequeDouble-ended queue allowing element addition/removal from both ends. Implementation: ArrayDeque.

5. Conclusion​

  • The Collection interface provides essential methods for managing groups of objects.
  • List, Set, Queue, and Deque extend Collection, offering specialized functionalities.
  • Understanding and using these methods efficiently improves Java programming skills.

By utilizing the Collection interface, developers can write more flexible and reusable code!

Java Collection Framework - Overview & Advantages

1. Introduction​

The Collection Framework is a pre-defined set of classes, interfaces, and methods in Java that helps in efficiently managing large volumes of data. While variables can store small amounts of data, arrays were introduced to store multiple elements. However, arrays have several limitations, which led to the development of the Collection Framework.

2. Limitations of Arrays​

  • Stores Only Homogeneous Data: Arrays can only store elements of the same data type.
  • Fixed Size: Once an array is created, its size cannot be changed.
  • Uses Continuous Memory Locations: Arrays store elements in contiguous memory, which can lead to memory wastage or allocation issues.

3. Advantages of the Collection Framework​

  • Overcomes Array Limitations: Can store heterogeneous (different types of) data.
  • Dynamic Sizing: Collection classes like ArrayList and LinkedList can grow or shrink dynamically.
  • Efficient Data Handling: Provides various data structures like Lists, Sets, and Queues for different use cases.
  • Predefined Methods: Comes with built-in methods for sorting, searching, and manipulating data.

4. Main Classes in the Collection Framework​

ClassDescription
ArrayListA resizable array implementation of the List interface.
LinkedListA doubly-linked list implementation, suitable for frequent insertions and deletions.
HashSetA collection that stores unique elements with no specific order.
TreeSetA sorted collection that maintains elements in ascending order.
HashMapA key-value pair storage that allows fast retrieval of elements.
TreeMapA sorted key-value storage that keeps keys in ascending order.
PriorityQueueA queue that processes elements based on priority rather than insertion order.

5. Conclusion​

The Java Collection Framework provides a flexible, efficient, and powerful way to manage data structures. It simplifies programming tasks by offering ready-made solutions for data storage, retrieval, and manipulation.

By leveraging these classes, developers can write optimized and maintainable Java applications!

Notes on Java ArrayList

1. Introduction to ArrayList:

  • Part of Java Collection Framework.
  • Allows dynamic resizing.
  • Stores heterogeneous data types.
  • Maintains the order of insertion.
  • Uses a dynamic array internally.

2. Key Operations:

  • add(element): Adds an element to the end.
  • add(index, element): Inserts an element at a specific index (shifts elements).
  • set(index, element): Replaces an existing element at a given index.
  • get(index): Retrieves an element from a specific index.
  • contains(element): Checks if an element exists in the list.
  • remove(element): Removes the first occurrence of an element.
  • remove(index): Removes the element at a specific index.
  • addAll(collection): Adds all elements from another collection.
  • clear(): Removes all elements from the list.

3. Example Usage:

  • Creating an ArrayList:

    ArrayList<Object> list = new ArrayList<>();
  • Adding elements:

    list.add(1); // Integer
    list.add("Hello"); // String
    list.add(3.14); // Double
    list.add(true); // Boolean
    list.add('A'); // Character
  • Adding element at a specific index:

    list.add(0, 24); // Inserts 24 at index 0
  • Replacing an element:

    list.set(1, "World"); // Replaces "Hello" with "World"
  • Retrieving an element:

    list.get(2);
  • Checking for an element:

    list.contains(30);
  • Removing an element:

    list.remove((Object)3.14);
  • Removing an element by index:

    list.remove(1);
  • Adding another collection:

    ArrayList<Object> list2 = new ArrayList<>();
    list2.add("Java");
    list2.add(42);
    list2.add(99.99);
    list2.add(false);
    list.addAll(list2);
  • Iterating through an ArrayList using different methods:

    Using for-each loop:

    for (Object ele : list) {
    System.out.println(ele);
    }

    Using for loop:

    for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
    }

    Using Iterator:

    Iterator<Object> iterator = list.iterator();
    while (iterator.hasNext()) {
    System.out.println(iterator.next());
    }

    Using ListIterator (forward and backward traversal):

    ListIterator<Object> listIterator = list.listIterator();
    System.out.println("Forward Iteration:");
    while (listIterator.hasNext()) {
    System.out.println(listIterator.next());
    }

    System.out.println("Backward Iteration:");
    while (listIterator.hasPrevious()) {
    System.out.println(listIterator.previous());
    }

    Using Streams (Java 8+):

    list.stream().forEach(System.out::println);
  • Clearing the list:

    list.clear();

Iterators in Collection-Based Classes​

Iterators are provided for collection-based classes to allow traversal through elements. They function similarly to cursors, starting just before the first element when created.

Key Methods of Iterators:​

  1. hasNext()

    • Returns true if there are more elements in the collection.
    • Returns false if no more elements are present.
    • Does not move the iterator.
  2. next()

    • Moves the iterator to the next element.
    • Returns the element at the new position.

Benefits of Iterators​

  • They provide a consistent way to access elements in a collection.
  • Useful for traversing data structures like lists, sets, and maps.
  • Help avoid common pitfalls of manual indexing.

Using Iterators with ArrayList​

Iterators can be used to traverse an ArrayList efficiently:

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<>();
myList.add("Apple");
myList.add("Banana");
myList.add("Cherry");

Iterator<String> iterator = myList.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
}
}

This ensures safe and efficient traversal of an ArrayList using an iterator.

ArrayDeque in Collection Framework​

ArrayDeque (Array Double-Ended Queue) is a class in the Java Collection Framework that allows adding and removing elements from both the front and the back. It internally implements a resizable array-based double-ended queue.

Key Features of ArrayDeque:​

  • Allows insertion and deletion from both ends.
  • Unlike ArrayList, it does not support index-based access.
  • Maintains the order of insertion.
  • Capable of storing heterogeneous data.
  • Faster than LinkedList for queue operations.
  • No capacity restrictions (resizable array).

Methods in ArrayDeque​

  1. addFirst(E e) - Adds an element at the front.
  2. addLast(E e) - Adds an element at the back.
  3. getFirst() - Retrieves the first element without removing it.
  4. getLast() - Retrieves the last element without removing it.
  5. removeFirst() - Removes and returns the first element.
  6. removeLast() - Removes and returns the last element.

Example Usage of ArrayDeque​

import java.util.ArrayDeque;

public class ArrayDequeExample {
public static void main(String[] args) {
ArrayDeque<String> deque = new ArrayDeque<>();

// Adding elements
deque.addFirst("Apple");
deque.addLast("Banana");
deque.addFirst("Cherry");

// Retrieving elements
System.out.println("First Element: " + deque.getFirst());
System.out.println("Last Element: " + deque.getLast());

// Removing elements
deque.removeFirst();
deque.removeLast();

// Printing all elements
System.out.println("Remaining Elements: " + deque);
}
}

This example demonstrates adding, retrieving, and removing elements from an ArrayDeque.

LinkedList in Collection Framework​

LinkedList is a class in the Java Collection Framework used when efficient insertion and deletion at arbitrary positions are required. Unlike ArrayList, which allows random access but has expensive insertions and deletions, LinkedList is optimized for dynamic modifications.

Key Features of LinkedList:​

  • Each element in a LinkedList is stored as a node containing:
    • The data element.
    • A reference to the previous node.
    • A reference to the next node.
  • Supports index-based access like ArrayList.
  • Maintains the order of insertion.
  • Efficient for frequent insertions and deletions at random positions.
  • Utilizes scattered memory efficiently.

Methods in LinkedList​

  1. addFirst(E e) - Adds an element at the front.
  2. addLast(E e) - Adds an element at the back.
  3. add(int index, E e) - Inserts an element at a specific index.
  4. getFirst() - Retrieves the first element.
  5. getLast() - Retrieves the last element.
  6. removeFirst() - Removes and returns the first element.
  7. removeLast() - Removes and returns the last element.
  8. remove(int index) - Removes the element at a specific index.

Example Usage of LinkedList​

1. Basic LinkedList Operations​

import java.util.LinkedList;

public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();

// Adding elements
list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.addFirst("Mango");
list.addLast("Grapes");
list.add(2, "Orange");

// Retrieving elements
System.out.println("First Element: " + list.getFirst());
System.out.println("Last Element: " + list.getLast());

// Removing elements
list.removeFirst();
list.removeLast();
list.remove(2);

// Printing all elements
System.out.println("Remaining Elements: " + list);
}
}

2. Using LinkedList as a Queue​

import java.util.LinkedList;
import java.util.Queue;

public class LinkedListQueueExample {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();

// Adding elements to the queue
queue.add(10);
queue.add(20);
queue.add(30);

// Retrieving and removing elements
System.out.println("Head: " + queue.peek());
queue.poll();

// Printing remaining elements
System.out.println("Queue after removal: " + queue);
}
}

This demonstrates various operations using LinkedList efficiently.

PriorityQueue in Collection Framework​

PriorityQueue is a class in the Java Collection Framework that does not maintain the order of insertion but instead arranges elements based on their priority. It follows a min-heap data structure by default, meaning the smallest element is always at the top.

Key Features of PriorityQueue:​

  • Does not maintain the order of insertion.
  • Returns elements based on priority (default is natural ordering, but custom comparators can be used).
  • Internally implements a min-heap.
  • Does not allow heterogeneous data at runtime (results in ClassCastException).
  • Does not permit null values.

Methods in PriorityQueue​

  1. add(E e) - Inserts an element into the queue.
  2. offer(E e) - Similar to add(), but returns false if insertion fails.
  3. peek() - Retrieves the highest-priority element without removing it.
  4. poll() - Retrieves and removes the highest-priority element.
  5. remove(Object o) - Removes a specific element.
  6. size() - Returns the number of elements in the queue.

Example Usage of PriorityQueue​

1. Default PriorityQueue (Min-Heap)​

import java.util.PriorityQueue;

public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();

// Adding elements
pq.add(40);
pq.add(10);
pq.add(30);
pq.add(20);

// Retrieving elements based on priority
System.out.println("Top Element: " + pq.peek());

// Removing elements
while (!pq.isEmpty()) {
System.out.println("Removed: " + pq.poll());
}
}
}

2. Custom Comparator for Max-Heap​

import java.util.PriorityQueue;
import java.util.Collections;

public class MaxHeapExample {
public static void main(String[] args) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

// Adding elements
maxHeap.add(40);
maxHeap.add(10);
maxHeap.add(30);
maxHeap.add(20);

// Removing elements
while (!maxHeap.isEmpty()) {
System.out.println("Removed: " + maxHeap.poll());
}
}
}

3. Handling ClassCastException with Heterogeneous Data​

import java.util.PriorityQueue;

public class ClassCastExceptionExample {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue(); // Raw type (not recommended)
queue.add("Apple");
queue.add(10); // Mixing types (will cause runtime exception)

while (!queue.isEmpty()) {
System.out.println(queue.poll()); // Throws ClassCastException
}
}
}

This demonstrates how PriorityQueue works and why it does not support heterogeneous data at runtime.

TreeSet in Collection Framework​

TreeSet is a class in the Java Collection Framework that is used to store sorted data. It implements the SortedSet interface and uses a Red-Black Tree, which is a self-balancing binary search tree.

Key Features of TreeSet:​

  • Maintains elements in sorted order.
  • Uses a Red-Black Tree for balancing.
  • Does not allow duplicate elements.
  • Does not allow heterogeneous data (results in ClassCastException at runtime if mixed types are added).
  • Does not allow null values.
  • Provides logarithmic time complexity for insertion, deletion, and search operations.

Methods in TreeSet​

  1. add(E e) - Adds an element while maintaining sorting order.
  2. remove(Object o) - Removes the specified element.
  3. first() - Retrieves the first (smallest) element.
  4. last() - Retrieves the last (largest) element.
  5. ceiling(E e) - Returns the smallest element greater than or equal to the given element.
  6. floor(E e) - Returns the largest element less than or equal to the given element.
  7. headSet(E toElement) - Returns elements strictly less than the given element.
  8. tailSet(E fromElement) - Returns elements greater than or equal to the given element.

Example Usage of TreeSet​

1. Basic TreeSet Example​

import java.util.TreeSet;

public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> treeSet = new TreeSet<>();

// Adding elements
treeSet.add(40);
treeSet.add(10);
treeSet.add(30);
treeSet.add(20);

// Retrieving elements
System.out.println("Sorted Set: " + treeSet);
System.out.println("First Element: " + treeSet.first());
System.out.println("Last Element: " + treeSet.last());

// Removing an element
treeSet.remove(30);
System.out.println("After Removing 30: " + treeSet);
}
}

2. Handling ClassCastException with Heterogeneous Data​

import java.util.TreeSet;

public class ClassCastExceptionExample {
public static void main(String[] args) {
TreeSet treeSet = new TreeSet(); // Raw type (not recommended)
treeSet.add("Apple");
treeSet.add(10); // Mixing types (will cause runtime exception)

System.out.println(treeSet); // Throws ClassCastException
}
}

This demonstrates how TreeSet works, including sorting, retrieval, and handling the ClassCastException caused by adding heterogeneous data.

HashSet and LinkedHashSet in Collection Framework​

Set is a collection that does not allow duplicate elements. There are different types of Set implementations in Java, each with unique properties.

Key Differences Between HashSet, LinkedHashSet, and TreeSet:​

  1. HashSet:

    • Does not maintain the order of insertion.
    • Internally uses a HashMap.
    • Best suited when order does not matter and fast lookups are needed.
  2. LinkedHashSet:

    • Maintains the insertion order.
    • Internally uses a LinkedHashMap.
    • Best suited when order needs to be preserved.
  3. TreeSet:

    • Maintains sorted order.
    • Internally uses a Red-Black Tree.
    • Best suited when sorting is required.

Methods in HashSet and LinkedHashSet​

  1. add(E e) - Adds an element to the set.
  2. remove(Object o) - Removes the specified element.
  3. contains(Object o) - Checks if an element is present.
  4. size() - Returns the number of elements.
  5. clear() - Removes all elements.

Example Usage of HashSet​

import java.util.HashSet;

public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();

// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicate will not be added

// Printing elements
System.out.println("HashSet Elements: " + set);
}
}

Example Usage of LinkedHashSet​

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<String> linkedSet = new LinkedHashSet<>();

// Adding elements
linkedSet.add("Apple");
linkedSet.add("Banana");
linkedSet.add("Cherry");
linkedSet.add("Apple"); // Duplicate will not be added

// Printing elements (maintains insertion order)
System.out.println("LinkedHashSet Elements: " + linkedSet);
}
}

This demonstrates the differences between HashSet and LinkedHashSet, explaining when to use each based on data order and uniqueness requirements.

Summary of Collection Framework Classes​

The Java Collection Framework provides various classes to store and manage data efficiently. Below is a summary of commonly used collection classes, their properties, and whether they support heterogeneous data.

Collection Classes Overview​

ClassMaintains OrderAllows DuplicatesAllows Heterogeneous DataInternal Implementation
ArrayList✅ Yes✅ Yes✅ YesDynamic Array
LinkedList✅ Yes✅ Yes✅ YesDoubly Linked List
HashSet❌ No❌ No✅ YesHashMap
LinkedHashSet✅ Yes❌ No✅ YesLinkedHashMap
TreeSet✅ Yes (Sorted)❌ No❌ NoRed-Black Tree
PriorityQueue❌ No✅ Yes❌ NoMin-Heap
ArrayDeque✅ Yes✅ Yes✅ YesDoubly Ended Queue

Example Implementations​

1. ArrayList Example​
import java.util.ArrayList;

public class ArrayListExample {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("Hello");
list.add(100);
list.add(3.14);
System.out.println("ArrayList: " + list);
}
}
2. LinkedList Example​
import java.util.LinkedList;

public class LinkedListExample {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("World");
list.add(200);
list.add(2.71);
System.out.println("LinkedList: " + list);
}
}
3. HashSet Example​
import java.util.HashSet;

public class HashSetExample {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add("Apple");
set.add(50);
set.add(2.5);
System.out.println("HashSet: " + set);
}
}
4. LinkedHashSet Example​
import java.util.LinkedHashSet;

public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet set = new LinkedHashSet();
set.add("Banana");
set.add(75);
set.add(1.99);
System.out.println("LinkedHashSet: " + set);
}
}
5. TreeSet Example (Cannot Store Heterogeneous Data)​
import java.util.TreeSet;

public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
set.add(10);
set.add(5);
set.add(20);
System.out.println("TreeSet: " + set);
}
}
6. PriorityQueue Example (Cannot Store Heterogeneous Data)​
import java.util.PriorityQueue;

public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(30);
pq.add(10);
pq.add(20);
System.out.println("PriorityQueue: " + pq);
}
}
7. ArrayDeque Example​
import java.util.ArrayDeque;

public class ArrayDequeExample {
public static void main(String[] args) {
ArrayDeque queue = new ArrayDeque();
queue.addFirst("Start");
queue.addLast("End");
queue.add(50);
queue.add(3.14);
System.out.println("ArrayDeque: " + queue);
}
}

This summary provides an overview of Java Collection Framework classes, their properties, and examples demonstrating their usage.