Dr. Vatsal Shah
Subject Material

Java · Collections · Topic 1

Introduction to the Java Collection Framework

Understand why collections are needed, how the framework is organized, and how Collection and Map differ from arrays and from each other.

Topic progress · 1 of 10 sections

Step 1 of 10

1.1 What is a collection?

Learning objective

Define a collection and recognize the different ways Java can organize groups of objects.

A collection is an object that stores and manages a group of objects.

For example, an ArrayList can keep several student names inside one manageable object.

A simple collection of student names
ArrayList<String> students = new ArrayList<>();

students.add("Amit");
students.add("Neha");
students.add("Raj");

Here, students is a collection that stores multiple String objects.

Java provides structures for different requirements

  • Ordered data
  • Unique data
  • Key-value pairs
  • First-in-first-out data
  • Sorted data
Check your understanding: If student names may repeat and their order matters, which storage behavior is required?

Ordered data that allows duplicates, normally represented by a List such as ArrayList.

Step 2 of 10

1.2 Need for collections

Learning objective

Explain the limitations of arrays and select a suitable collection for a storage requirement.

Before the Collection Framework, arrays were commonly used to store multiple values.

Storing student names in an array
String[] students = new String[3];

students[0] = "Amit";
students[1] = "Neha";
students[2] = "Raj";

Fixed size

The size of an array must be specified when it is created. An array declared with five positions can store exactly five values, and its length cannot later grow or shrink.

A collection such as ArrayList can grow and shrink during program execution.

A dynamically growing collection
ArrayList<Integer> numbers = new ArrayList<>();

numbers.add(10);
numbers.add(20);
numbers.add(30);

Limited built-in operations

Arrays do not directly provide convenient methods for adding, removing, searching, sorting, reversing, or checking whether an element exists. Collections provide ready-made operations.

Ready-made collection operations
numbers.add(40);
numbers.remove(Integer.valueOf(20));
numbers.contains(30);
numbers.sort(null);

Different applications need different storage behavior

  • A list of student names may contain duplicates.
  • Enrollment numbers must be unique.
  • A waiting line should follow FIFO order.
  • Student information may use enrollment numbers as keys.
Requirement and suitable collection
RequirementSuitable collection
Ordered data with duplicatesArrayList
Unique elementsHashSet
Sorted unique elementsTreeSet
Key-value pairsHashMap
FIFO processingQueue
LIFO processingStack or Deque
Check your understanding: Which collection is a natural choice for unique values that must remain sorted?

TreeSet.

Step 3 of 10

1.3 Advantages of the Collection Framework

Learning objective

Describe the main benefits of using the Collection Framework in Java programs.

Core advantages

  • Dynamic size: collections can grow or shrink during execution.
  • Reusable data structures: Java provides ArrayList, LinkedList, HashSet, TreeSet, HashMap, PriorityQueue, and more.
  • Standard methods: familiar operations include add(), remove(), contains(), size(), isEmpty(), and clear().
  • Easy processing: collections work with iterators, generics, lambda expressions, streams, and utility methods.

Type safety using generics

Generics specify which type of object a collection can store. This prevents many incorrect values from reaching the program at runtime.

Only String objects are accepted
ArrayList<String> names = new ArrayList<>();

names.add("Amit");  // Valid
// names.add(100);   // Compilation error

Better program design

The framework is designed around interfaces. Code can depend on the List interface while the selected implementation changes.

Program to the interface
List<String> names = new ArrayList<>();

// The implementation can later be changed:
List<String> otherNames = new LinkedList<>();
Check your understanding: How do generics make an ArrayList<String> safer?

They restrict the collection to String values and make incompatible additions a compile-time error.

Step 4 of 10

1.4 Main components of the Collection Framework

Learning objective

Distinguish interfaces, implementation classes, and algorithms in the framework.

The Collection Framework consists mainly of interfaces, implementation classes, and algorithms or utility methods.

Interfaces define supported operations

  • Collection
  • List
  • Set
  • Queue
  • Deque
  • Map

Implementation classes provide the actual data structures.

Common interfaces and implementations
InterfaceCommon implementation classes
ListArrayList, LinkedList, Vector, Stack
SetHashSet, LinkedHashSet, TreeSet
QueuePriorityQueue, LinkedList
DequeArrayDeque, LinkedList
MapHashMap, LinkedHashMap, TreeMap, Hashtable

Algorithms and utility methods

The Collections utility class provides algorithms for processing collections.

Utility operations
Collections.sort(list);
Collections.reverse(list);
Collections.shuffle(list);
Collections.max(list);
Collections.min(list);
Check your understanding: In List<String> names = new ArrayList<>(), which name is the interface and which is the implementation?

List is the interface and ArrayList is the implementation class.

Step 5 of 10

1.5 Collection Framework hierarchy

Learning objective

Read the main Collection and Map relationships and recognize interfaces, abstract classes, concrete classes, and legacy classes.

The framework has a Collection hierarchy for groups of elements, a separate Map hierarchy for key-value pairs, and supporting interfaces used for traversal and ordering.

Java Collection Framework hierarchy

Map does not extend Collection.

Collection hierarchy

Iterable<E>
extends
Collection<E>
Collection<E>
extends
List<E>
List<E>
implements
AbstractList<E>
AbstractList<E>
extends
ArrayList<E>
AbstractList<E>
extends
Vector<E>
Vector<E>
extends
Stack<E>
AbstractList<E>
extends
AbstractSequentialList<E>
AbstractSequentialList<E>
extends
LinkedList<E>also implements Deque
Collection<E>
extends
Set<E>
Set<E>
implements
AbstractSet<E>
AbstractSet<E>
extends
HashSet<E>
HashSet<E>
extends
LinkedHashSet<E>
Set<E>
extends
SortedSet<E>
SortedSet<E>
extends
NavigableSet<E>
NavigableSet<E>
implements
TreeSet<E>extends AbstractSet
Collection<E>
extends
Queue<E>
Queue<E>
implements
AbstractQueue<E>
AbstractQueue<E>
extends
PriorityQueue<E>
Queue<E>
extends
Deque<E>
Deque<E>
implements
ArrayDeque<E>
Deque<E>
implements
LinkedList<E>also implements List

Map hierarchy

Map<K, V>
implements
AbstractMap<K, V>
AbstractMap<K, V>
extends
HashMap<K, V>
HashMap<K, V>
extends
LinkedHashMap<K, V>
Map<K, V>
extends
SortedMap<K, V>
SortedMap<K, V>
extends
NavigableMap<K, V>
NavigableMap<K, V>
implements
TreeMap<K, V>extends AbstractMap
Dictionary<K, V>
extends
Hashtable<K, V>implements Map
Hashtable<K, V>
extends
Properties
ConcurrentMap<K, V>
implements
ConcurrentHashMap<K, V>
ConcurrentMap<K, V>
extends
ConcurrentNavigableMap<K, V>
ConcurrentNavigableMap<K, V>
implements
ConcurrentSkipListMap<K, V>

Supporting interfaces

Iterator<E>
ListIterator<E>
Comparable<T>
Comparator<T>
RandomAccess
Spliterator<T>
InterfaceAbstract classConcrete classLegacy classConcurrent classSolid: extendsDashed: implements
Check your understanding: Why is Map shown separately from Collection?

Collection stores individual elements, while Map stores key-value pairs and therefore does not extend Collection.

Step 6 of 10

1.6 The Iterable interface

Learning objective

Explain how Iterable enables enhanced-for-loop traversal.

Iterable is the root interface that allows an object to be used in an enhanced for loop.

Enhanced for-loop traversal
for (String name : names) {
    System.out.println(name);
}

The Collection interface extends Iterable. Therefore, objects such as ArrayList, LinkedList, and HashSet can be traversed using an enhanced for loop.

Check your understanding: Which root interface makes an object usable in an enhanced for loop?

Iterable.

Step 7 of 10

1.7 The Collection interface

Learning objective

Use the common operations declared by Collection and trace a complete Collection program.

Collection is the main root interface for storing a group of individual objects.

Declare through the Collection interface
Collection<String> names = new ArrayList<>();
Important Collection methods
MethodPurpose
add(element)Adds an element
addAll(collection)Adds all elements of another collection
remove(element)Removes an element
removeAll(collection)Removes matching elements
retainAll(collection)Keeps only common elements
contains(element)Checks whether an element exists
containsAll(collection)Checks whether all elements exist
size()Returns the number of elements
isEmpty()Checks whether the collection is empty
clear()Removes all elements
iterator()Returns an iterator
toArray()Converts the collection into an array
CollectionDemo.java
import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo {
    public static void main(String[] args) {
        Collection<String> subjects = new ArrayList<>();

        subjects.add("Java");
        subjects.add("Python");
        subjects.add("Database");

        System.out.println(subjects);
        System.out.println("Size: " + subjects.size());
        System.out.println("Contains Java: " +
                           subjects.contains("Java"));

        subjects.remove("Python");

        System.out.println("After removal: " + subjects);
    }
}
Output
[Java, Python, Database]
Size: 3
Contains Java: true
After removal: [Java, Database]
Check your understanding: Which method checks whether a Collection contains a particular element?

contains(element).

Step 8 of 10

1.8 The Map interface

Learning objective

Store, retrieve, and traverse key-value pairs with the Map interface.

A Map stores data in the form of key-value pairs.

Enrollment numbers as keys
Enrollment number — KeyStudent name — Value
101Amit
102Neha
103Raj
Create and populate a Map
Map<Integer, String> students = new HashMap<>();

students.put(101, "Amit");
students.put(102, "Neha");
students.put(103, "Raj");

Important Map characteristics

  • Every key must be unique.
  • Values may be duplicated.
  • Each key is associated with one value.
  • Adding another value with the same key replaces the old value.
Replacing a value
students.put(101, "Amit");
students.put(101, "Rahul");
// Key 101 is now associated with "Rahul".
Important Map methods
MethodPurpose
put(key, value)Adds or updates an entry
putAll(map)Adds all entries from another map
get(key)Returns the value associated with a key
getOrDefault(key, defaultValue)Returns a value or a default value
remove(key)Removes an entry
containsKey(key)Checks whether a key exists
containsValue(value)Checks whether a value exists
replace(key, value)Replaces the value of a key
keySet()Returns all keys
values()Returns all values
entrySet()Returns all key-value entries
size()Returns the number of entries
isEmpty()Checks whether the map is empty
clear()Removes all entries
MapDemo.java
import java.util.HashMap;
import java.util.Map;

public class MapDemo {
    public static void main(String[] args) {
        Map<Integer, String> students = new HashMap<>();

        students.put(101, "Amit");
        students.put(102, "Neha");
        students.put(103, "Raj");

        System.out.println("Student 102: " + students.get(102));
        System.out.println("Contains key 101: " +
                           students.containsKey(101));

        for (Map.Entry<Integer, String> entry
                : students.entrySet()) {
            System.out.println(entry.getKey() +
                               " : " + entry.getValue());
        }
    }
}
Possible output
Student 102: Neha
Contains key 101: true
101 : Amit
102 : Neha
103 : Raj
Check your understanding: What happens when put() is called twice with the same key?

The later value replaces the value previously associated with that key.

Step 9 of 10

1.9 Difference between Collection and Map

Learning objective

Compare the storage model and core operations of Collection and Map.

Collection and Map compared
CollectionMap
Stores individual elementsStores key-value pairs
Root interface for List, Set, and QueueA separate interface
Uses add() to insert elementsUses put() to insert entries
Accesses individual objectsAccesses values through keys
May allow duplicate elementsKeys cannot be duplicated
Example: list of namesExample: enrollment number and name
Check your understanding: Which insertion method belongs to Map rather than Collection?

put(key, value).

Step 10 of 10

1.10 Difference between arrays and collections

Learning objective

Choose between an array and a collection and explain wrapper types and autoboxing.

Arrays and collections compared
ArrayCollection
Has a fixed sizeCan grow and shrink dynamically
Can store primitive values and objectsStores objects; wrapper classes represent primitive values
Uses the length propertyUses the size() method
Provides few direct operationsProvides many predefined methods
Can be multidimensionalNormally one-dimensional structures that can be nested
May be faster for simple indexed accessProvides more flexibility
Type is written as int[] or String[]Uses generics such as List<Integer>
Elements are accessed using indexesAccess depends on the collection type
May store duplicate valuesDuplicate handling depends on the collection type
Array and collection syntax
int[] array = new int[3];
array[0] = 10;

ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);

Primitive values in collections

Collections cannot directly use primitive types as generic type arguments. Wrapper classes such as Integer represent primitive values as objects.

Use the Integer wrapper type
// Incorrect:
// ArrayList<int> numbers = new ArrayList<>();

// Correct:
ArrayList<Integer> numbers = new ArrayList<>();

// Autoboxing converts primitive int 10 to an Integer object.
numbers.add(10);
Check your understanding: Why is ArrayList<int> invalid while ArrayList<Integer> is valid?

Generic type arguments must be reference types, so the Integer wrapper is used instead of primitive int.