Collection Framework in Java: Complete Guide with Examples
Collections are used in almost every programming language. Most languages support various types of collections such as List, Set, Queue, and Stack. In this guide, you will learn the Java Collection Framework in detail — its interfaces, classes, methods, and advantages.
What is a Collection?
A Collection is a group of objects.
A Framework is a pre-defined architecture where we can manipulate a group of objects.
Java 1.2 provided a Collection Framework that is used to provide sorting, searching, and manipulation of a group of objects. The Collection Framework provides a set of interfaces and classes and also provides implementations of algorithms.
All classes and interfaces of the Collection Framework exist in the
java.util package.
Why Collection Framework?
The Java Collections Framework has the following advantages:
- Reduced development effort by using core collection classes rather than implementing your own collection classes.
- Code quality is enhanced with the use of well-tested Collections Framework classes.
- Reduced effort for code maintenance by using collection classes shipped with the JDK.
- Re-usability and interoperability.
Forms of Collection
There are two forms of a collection:
- Generic Collection
- Non-Generic Collection
Generic Collection
A group of similar or homogeneous type of objects is called a Generic Collection.
For example: List<String> list = new ArrayList<String>();
In the above collection, we can have String type of objects only.
Non-Generic Collection
A group of dissimilar or heterogeneous type of objects is called a Non-Generic Collection.
For example: List list = new ArrayList();
In the above collection, we can have any type of objects.
Difference Between Array and Collection
| Array | Collection |
|---|---|
| Array size is fixed. | Collection is re-sizable. |
| Array can hold homogeneous data type. | Collection can be homogeneous or heterogeneous. |
| Array can hold primitive and non-primitive data type. | Collection can hold non-primitive data type (Objects). |
| Array is faster than Collection. | Collection is slower than an array. |
| If you know the size of elements, then go for array. | If you don't know the size of elements, then go for collection. |
| In case of array, there are no ready-made methods available. | In case of collection, there are ready-made methods available. |
| In case of memory, array is not recommended. | In case of memory, collection is recommended. |
Hierarchy of Collection Framework
The Java Collection Framework follows this interface hierarchy:
Iterable Interface
- It is the root class of the Collection Framework.
- This interface exists in the
java.langpackage. - It has an
iterator()method which is used to iterate a collection. -
This
iterator()method returns anIteratorinterface object which exists in thejava.utilpackage.
Iterator Interface
- The Iterator interface provides methods to iterate over any Collection. We can get an iterator instance from a Collection using the
iterator()method. - Iterators allow the caller to remove elements from the underlying collection during the iteration.
- Iterators in collection classes implement the Iterator Design Pattern.
Iterator Methods
| Method | Description |
|---|---|
hasNext() | Tests whether the next element is available in the collection or not during iteration. |
next() | Returns an element from a collection during iteration. |
remove() | Removes an element from the collection during iteration. |
Collection Interface
Collection is a sub-interface of the Iterable interface, which has the following methods to perform different operations.
| Method | Description |
|---|---|
size() | Used to get the length of a collection. |
isEmpty() | Tests whether the collection is empty or not. |
contains() | Finds an element from a collection. |
toArray() | Used to convert a collection into an array. |
add() | Used to add an element into the collection. |
remove() | Used to remove an element from the collection. |
clear() | Used to remove all elements from the collection. |
addAll() | Used to add one collection into another collection. |
removeAll() | Used to remove a collection from another collection. |
retainAll() | Used to remove all collection elements except those in the retained collection. |
containsAll() | Finds a collection from another collection. |
List Interface
- List is a sub-interface of the Collection interface.
- The List interface allows duplicate elements.
- The List interface is an ordered collection (sometimes called a sequence).
- The List interface is implemented by the ArrayList, LinkedList, and Vector classes.
List Methods
| Method | Description |
|---|---|
get() | Used to get an element based on index from the collection. |
set() | Used to replace an element based on index in the collection. |
indexOf() | Used to get the index based on the element. |
lastIndexOf() | Used to get the index based on the last occurrence of the element. |
subList() | Used to get a sublist based on a from-index and to-index. |
listIterator() | Used to iterate elements in both directions — forward and backward. |
Queue Interface
- Queue is a sub-interface of the Collection interface.
- The Queue interface holds elements in FIFO (First In First Out) order.
- The Queue interface is implemented by the PriorityQueue class.
Queue Methods
| Method | Description |
|---|---|
add() | Used to add an element to the Queue. |
offer() | Used to add an element to the Queue. |
remove() | Used to get and remove the element at the top of the Queue. |
poll() | Used to get and remove the element at the top of the Queue; returns null if the Queue is empty. |
element() | Used to get the element at the top of the Queue. |
peek() | Used to get the element at the top of the Queue; returns null if the Queue is empty. |
Deque Interface
- Deque is a sub-interface of the Queue interface.
- In a Deque, we can insert and delete elements from both ends.
- Methods are provided to insert, remove, and examine the element.
-
Each of these methods exists in two forms:
- One throws an exception if the operation fails.
- The other returns a special value (either null or false, depending on the operation).
- The Deque interface is implemented by the ArrayDeque class.
Deque Methods
| Method | Description |
|---|---|
addFirst() | Used to add an element at the beginning. |
addLast() | Used to add an element at the end. |
offerFirst() | Used to add an element at the beginning and returns true or false. |
offerLast() | Used to add an element at the end and returns true or false. |
removeFirst() | Removes the first element; throws NoSuchElementException if the deque is empty. |
removeLast() | Removes the last element; throws NoSuchElementException if the deque is empty. |
pollFirst() | Removes the first element; returns null if the deque is empty. |
pollLast() | Removes the last element; returns null if the deque is empty. |
getFirst() | Gets the top element; throws NoSuchElementException if the deque is empty. |
getLast() | Gets the last element; throws NoSuchElementException if the deque is empty. |
peekFirst() | Gets the top element; returns null if the deque is empty. |
peekLast() | Gets the last element; returns null if the deque is empty. |
removeFirstOccurrence() | Removes the first occurrence of an element. |
removeLastOccurrence() | Removes the last occurrence of an element. |
push() | Adds an element at the top of the Deque. |
pop() | Removes an element from the top. |
descendingIterator() | Used to iterate in descending order. |
Set Interface
- Set is a sub-interface of the Collection interface.
- The Set interface can never contain duplicate elements.
- The Set interface is implemented by the HashSet and TreeSet classes.
Set Methods
| Method | Description |
|---|---|
size() | Used to get the length of the collection. |
isEmpty() | Tests whether the collection is empty or not. |
contains() | Finds an element from a collection. |
toArray() | Used to convert a collection into an array. |
add() | Used to add an element into the collection. |
remove() | Used to remove an element from the collection. |
clear() | Used to remove all elements from the collection. |
addAll() | Used to add one collection into another collection. |
removeAll() | Used to remove a collection from another collection. |
retainAll() | Used to remove all collection elements except those in the retained collection. |
containsAll() | Finds a collection from another collection. |
Collections Class
The Java Collections class consists exclusively of static methods that
operate on or return collections. This class provides the following methods:
| Method | Description |
|---|---|
addAll() | Used to add elements to a specific collection. |
binarySearch() | Used to search the position of an element in a sorted list. |
copy() | Used to copy all elements from a source list to a destination list. |
frequency() | Returns the number of times an object appears in a collection. |
max() | Gets the maximum element or value from a collection. |
min() | Gets the minimum element or value from a collection. |
replaceAll() | Replaces all occurrences of one specified value in a list with another. |
reverse() | Reverses the order of list elements. |
rotate() | Rotates the elements in the specified list by a given distance. |
shuffle() | Randomly reorders the specified list elements. |
sort() | Sorts a list of elements. |
swap() | Swaps one element with another based on position in the list. |
synchronized...() | Makes a collection or map thread-safe. |
unmodifiable...() | Makes a collection or map immutable. |
Frequently Asked Questions
What is the Collection Framework in Java?
The Java Collection Framework is a pre-defined architecture introduced in Java 1.2 that
provides interfaces and classes to store and manipulate a group of objects. It offers
sorting, searching, and other data-processing operations and lives in the
java.util package.
What is the difference between Array and Collection in Java?
An array has a fixed size and can hold homogeneous primitive or non-primitive data, whereas a Collection is re-sizable and can hold homogeneous or heterogeneous objects. Collections provide ready-made methods and are recommended when the number of elements is unknown.
What is the difference between List and Set in Java?
A List allows duplicate elements and is ordered, whereas a Set does not allow duplicates. List is implemented by ArrayList, LinkedList, and Vector; Set is implemented by HashSet and TreeSet.
What is the difference between Queue and Deque in Java?
A Queue follows FIFO (First In, First Out) order, while a Deque (double-ended queue) allows insertion and removal at both ends. Queue is implemented by PriorityQueue; Deque is implemented by ArrayDeque.
What is the Collections class in Java?
The Collections class is a utility class in java.util that
contains only static methods to operate on collections, such as sort(),
reverse(), shuffle(), binarySearch(),
max(), min(), and synchronized variants.
Conclusion
The Java Collection Framework is a powerful architecture that provides reusable data
structures and algorithms out of the box. By understanding the hierarchy — Iterable →
Collection → List, Queue, Deque, and Set — and the utility methods in the
Collections class, you can write cleaner and more efficient Java code.
Related topics: Java ArrayList Tutorial, Java HashMap Tutorial, Java LinkedList Tutorial, Java TreeSet Tutorial, Java Generics, Java Iterator vs ListIterator
No comments:
Post a Comment