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.
Step 1 of 10
1.1 What is a collection?
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.
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
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.
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.
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.
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 | Suitable collection |
|---|---|
| Ordered data with duplicates | ArrayList |
| Unique elements | HashSet |
| Sorted unique elements | TreeSet |
| Key-value pairs | HashMap |
| FIFO processing | Queue |
| LIFO processing | Stack 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
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.
ArrayList<String> names = new ArrayList<>();
names.add("Amit"); // Valid
// names.add(100); // Compilation errorBetter program design
The framework is designed around interfaces. Code can depend on the List interface while the selected implementation changes.
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
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.
| Interface | Common implementation classes |
|---|---|
| List | ArrayList, LinkedList, Vector, Stack |
| Set | HashSet, LinkedHashSet, TreeSet |
| Queue | PriorityQueue, LinkedList |
| Deque | ArrayDeque, LinkedList |
| Map | HashMap, LinkedHashMap, TreeMap, Hashtable |
Algorithms and utility methods
The Collections utility class provides algorithms for processing collections.
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
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.
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
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.
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
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.
Collection<String> names = new ArrayList<>();| Method | Purpose |
|---|---|
| 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 |
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);
}
}[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
Store, retrieve, and traverse key-value pairs with the Map interface.
A Map stores data in the form of key-value pairs.
| Enrollment number — Key | Student name — Value |
|---|---|
| 101 | Amit |
| 102 | Neha |
| 103 | Raj |
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.
students.put(101, "Amit");
students.put(101, "Rahul");
// Key 101 is now associated with "Rahul".| Method | Purpose |
|---|---|
| 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 |
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());
}
}
}Student 102: Neha
Contains key 101: true
101 : Amit
102 : Neha
103 : RajCheck 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
Compare the storage model and core operations of Collection and Map.
| Collection | Map |
|---|---|
| Stores individual elements | Stores key-value pairs |
| Root interface for List, Set, and Queue | A separate interface |
| Uses add() to insert elements | Uses put() to insert entries |
| Accesses individual objects | Accesses values through keys |
| May allow duplicate elements | Keys cannot be duplicated |
| Example: list of names | Example: 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
Choose between an array and a collection and explain wrapper types and autoboxing.
| Array | Collection |
|---|---|
| Has a fixed size | Can grow and shrink dynamically |
| Can store primitive values and objects | Stores objects; wrapper classes represent primitive values |
| Uses the length property | Uses the size() method |
| Provides few direct operations | Provides many predefined methods |
| Can be multidimensional | Normally one-dimensional structures that can be nested |
| May be faster for simple indexed access | Provides more flexibility |
| Type is written as int[] or String[] | Uses generics such as List<Integer> |
| Elements are accessed using indexes | Access depends on the collection type |
| May store duplicate values | Duplicate handling depends on the collection type |
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.
// 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.