Arrays are useful for storing multiple values, but they come with an important limitation: their size must be fixed at the time of creation and cannot change afterward. In many real-world situations, you do not know in advance exactly how many items you will need to store, or that number may change frequently while the program is running.
To solve this problem, Java provides the Collections Framework, a set of ready-made classes and interfaces specifically designed for storing, organizing, and manipulating groups of objects efficiently. Unlike arrays, most collection types can grow or shrink dynamically as needed.
In this tutorial, you will learn about the core interfaces of the Collections Framework, including List, Set, Queue, and Map, along with their most commonly used implementations such as ArrayList, LinkedList, HashSet, and HashMap.
The Collections Framework is a unified architecture in Java that provides interfaces and classes for storing and processing groups of objects. It offers a consistent way to work with different kinds of data structures, allowing you to store, retrieve, sort, and manipulate collections of information using standardized methods.
import java.util.ArrayList;
public class CollectionsIntroExample {
public static void main(String[] args) {
ArrayList playlists = new ArrayList<>();
playlists.add("Java Basics");
playlists.add("Data Structures");
System.out.println("CS Engineering Gyan playlists: " + playlists);
}
}
CS Engineering Gyan playlists: [Java Basics, Data Structures]
Unlike a regular array, this ArrayList can grow automatically as more playlists are added, without requiring you to define its size in advance.
The Collections Framework is built around a small set of core interfaces, each representing a different way of organizing data.
| Interface | Description |
|---|---|
| List | Stores an ordered collection of elements that may contain duplicates. |
| Set | Stores a collection of unique elements with no duplicates allowed. |
| Queue | Stores elements in a specific order, typically for processing them one at a time. |
| Map | Stores data as key-value pairs, where each key is associated with a specific value. |
Each of these interfaces has multiple implementing classes, allowing you to choose the specific behavior and performance characteristics that best suit your particular use case.
ArrayList is one of the most commonly used implementations of the List interface. It stores elements in an ordered sequence, allows duplicate values, and automatically resizes itself as elements are added or removed.
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList videoTitles = new ArrayList<>();
videoTitles.add("Java OOPs Concepts");
videoTitles.add("Exception Handling in Java");
videoTitles.add("Collections Framework in Java");
System.out.println("CS Engineering Gyan videos: " + videoTitles);
System.out.println("First video: " + videoTitles.get(0));
videoTitles.remove("Exception Handling in Java");
System.out.println("Updated list: " + videoTitles);
}
}
CS Engineering Gyan videos: [Java OOPs Concepts, Exception Handling in Java, Collections Framework in Java] First video: Java OOPs Concepts Updated list: [Java OOPs Concepts, Collections Framework in Java]
ArrayList provides convenient methods such as add, get, and remove, making it easy to manage a growing collection of related items without worrying about manual resizing.
LinkedList is another implementation of the List interface, but it stores elements as a chain of connected nodes rather than a single continuous block of memory. This structure makes LinkedList particularly efficient for frequent insertions and deletions, especially at the beginning or middle of the list.
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList uploadQueue = new LinkedList<>();
uploadQueue.add("Java Loops Tutorial");
uploadQueue.add("Java Arrays Tutorial");
uploadQueue.addFirst("CS Engineering Gyan Channel Update");
System.out.println("Upload queue: " + uploadQueue);
}
}
Upload queue: [CS Engineering Gyan Channel Update, Java Loops Tutorial, Java Arrays Tutorial]
The addFirst method places a new element at the very beginning of the list, demonstrating one of the key advantages LinkedList offers over ArrayList when frequent insertions at specific positions are required.
| ArrayList | LinkedList |
|---|---|
| Faster for accessing elements by their index. | Faster for inserting or removing elements at the beginning or middle. |
| Stores elements in a resizable array structure. | Stores elements as a chain of connected nodes. |
| Generally preferred when read operations are more frequent. | Generally preferred when insertions and deletions are more frequent. |
HashSet is a commonly used implementation of the Set interface, designed to store a collection of unique elements. If you attempt to add a duplicate value, HashSet simply ignores it, ensuring that every element in the collection remains distinct.
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet uniqueTopics = new HashSet<>();
uniqueTopics.add("Java");
uniqueTopics.add("DBMS");
uniqueTopics.add("Java");
System.out.println("CS Engineering Gyan unique topics: " + uniqueTopics);
}
}
CS Engineering Gyan unique topics: [Java, DBMS]
Even though "Java" was added twice, the HashSet automatically ensures it appears only once in the final collection, making it an excellent choice whenever duplicate values need to be avoided.
HashMap is the most widely used implementation of the Map interface, storing data as key-value pairs. Each key in a HashMap must be unique, but the values associated with different keys can repeat freely.
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap videoViews = new HashMap<>();
videoViews.put("Java Basics", 5200);
videoViews.put("Java Loops", 4300);
videoViews.put("Java Arrays", 4800);
System.out.println("CS Engineering Gyan video views:");
for (String title : videoViews.keySet()) {
System.out.println(title + ": " + videoViews.get(title));
}
}
}
CS Engineering Gyan video views: Java Basics: 5200 Java Loops: 4300 Java Arrays: 4800
The put method adds a new key-value pair, while get retrieves the value associated with a specific key. The keySet method returns all the keys stored in the map, making it easy to loop through every entry.
The Queue interface represents a collection designed for holding elements before they are processed, typically following a first-in, first-out order. This means the first element added is generally the first one to be removed.
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue commentQueue = new LinkedList<>();
commentQueue.add("Great explanation on CS Engineering Gyan!");
commentQueue.add("Please make a video on Spring Boot.");
commentQueue.add("Loved the arrays tutorial.");
System.out.println("Processing: " + commentQueue.poll());
System.out.println("Remaining comments: " + commentQueue);
}
}
Processing: Great explanation on CS Engineering Gyan! Remaining comments: [Please make a video on Spring Boot., Loved the arrays tutorial.]
The poll method removes and returns the element at the front of the queue, simulating how comments or tasks might be processed one at a time, in the exact order they were received.
Java provides several ways to loop through the elements of a collection, with the enhanced for loop being one of the most common and readable approaches for most situations.
import java.util.ArrayList;
public class CollectionIterationExample {
public static void main(String[] args) {
ArrayList topics = new ArrayList<>();
topics.add("Arrays");
topics.add("Collections");
topics.add("Exception Handling");
System.out.println("CS Engineering Gyan upcoming topics:");
for (String topic : topics) {
System.out.println("- " + topic);
}
}
}
CS Engineering Gyan upcoming topics: - Arrays - Collections - Exception Handling
| Situation | Recommended Collection |
|---|---|
| Need an ordered list that allows duplicate values. | ArrayList or LinkedList |
| Need to store only unique values. | HashSet |
| Need to associate values with unique keys. | HashMap |
| Need to process elements in the order they were added. | Queue |
| Mistake | Correct Practice |
|---|---|
| Using an array when the collection size needs to change frequently. | Use ArrayList or LinkedList instead, since they resize automatically. |
| Expecting HashSet to maintain insertion order. | Remember that HashSet does not guarantee the order of its elements. |
| Using a duplicate key in a HashMap and expecting two separate entries. | Understand that adding a duplicate key simply overwrites the existing value. |
| Forgetting to import the required collection classes. | Always import classes from java.util before using ArrayList, HashMap, or similar types. |
The Collections Framework gives Java developers a powerful, flexible set of tools for managing groups of data far beyond what fixed-size arrays can offer. By understanding the core interfaces, List, Set, Queue, and Map, along with their common implementations like ArrayList, LinkedList, HashSet, and HashMap, you gain the ability to choose the right structure for almost any data-handling situation.
Each collection type offers its own strengths, whether that means fast index-based access, guaranteed uniqueness, efficient insertions, or convenient key-value associations. Learning to choose the appropriate collection based on your program's actual needs is an important skill for writing efficient, maintainable Java applications.
With a solid understanding of collections, you are now ready to explore file handling in Java, which allows programs to read from and write to files stored on a computer's file system.