The Collection Framework in Java provides interfaces and classes that implement data structures to store and manipulate collections of objects. It provides the programmer with a unified architecture to store and manipulate collections of objects.
The main interfaces in the Collection Framework are:
List - It maintains the insertion order and allows duplicates. Interfaces like ArrayList and LinkedList implement the List interface.
Set - It does not allow duplicates and does not maintain insertion order. Interfaces like HashSet and TreeSet implement the Set interface.
Queue - It implements the FIFO (First In First Out) principle and is used to represent waiting lines. Interfaces like PriorityQueue implements the Queue interface.
Map - It maps keys to values. Interfaces like HashMap and TreeMap implement the Map interface.
Let's take a closer look at some of the main collection interfaces and classes:
List Interface
The List interface provides the functionality of storing ordered collections of objects. The List interface is extended by the ArrayList and LinkedList classes.
//Creating an ArrayList
List<String> alist = new ArrayList<>();
alist.add("One");
alist.add("Two");
//Creating a LinkedList
List<String> llist = new LinkedList<>();
llist.add("One");
llist.add("Two");
ArrayList Class
The ArrayList class implements the List interface using an array. It is backed by an array and provides fast access and insertion in the middle of the list. It is the best option when there are frequent insertions and deletions in the middle of the list.
//Create an empty ArrayList
List<String> list = new ArrayList<>();
//Add elements
list.add("Hello");
list.add("World");
//Get element at index
String str = list.get(0);
//Check if list contains element
boolean contains = list.contains("Hello");
//Remove element
list.remove("Hello");
//Get size of list
int size = list.size();
//Use for loop
for (String s : list) {
System.out.println(s);
}
//Use iterator
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String s = iter.next();
System.out.println(s);
}
//Check if list is empty
boolean empty = list.isEmpty();
//Clear the list
list.clear();
Some key points about ArrayList:
It allows random access because the elements are stored in an array.
It is fast while accessing any element using the get() method.
It has slow remove() and add() operations because it rearranges elements for removing and adding an element.
The size of an ArrayList increases automatically.
It can store duplicate elements.
LinkedList Class
The LinkedList class also implements the List interface but uses a doubly linked list to store elements. It provides fast insertion and removal of elements at any position. It should be used when you need faster insertion and deletion compared to retrieval.
// Create an empty LinkedList
List<String> list = new LinkedList<>();
// Add elements
list.add("Hello");
list.add("World");
// Get element at index
String str = list.get(0);
// Check if list contains element
boolean contains = list.contains("Hello");
// Remove element
list.remove("Hello");
// Get size of list
int size = list.size();
// Use for loop
for (String s : list) {
System.out.println(s);
}
// Use iterator
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String s = iter.next();
System.out.println(s);
}
// Check if list is empty
boolean empty = list.isEmpty();
// Clear the list
list.clear();
Some key points about LinkedList:
It is slower than ArrayList for random access as it needs to traverse the links.
It has a fast add() and remove() operation as it only needs to adjust the links.
The size of a LinkedList does not increase automatically. It depends on the number of elements added.
It can store duplicate elements.
Set Interface
The Set interface provides the functionality of storing unordered collections of unique objects. The Set interface is extended by the HashSet and TreeSet classes.
HashSet Class
//Creating a HashSet
Set<String> hset = new HashSet<>();
hset.add("One");
hset.add("Two");
//Creating a TreeSet
Set<String> tset = new TreeSet<>();
tset.add("One");
tset.add("Two");
The HashSet class implements the Set interface using a hashtable. It uses the hashcode() method to determine the index of an object in the hashtable. Some key points about HashSet:
It provides fast access time because the elements are stored in a hashtable.
It does not maintain any particular order of elements. The elements can be accessed in any order.
It allows unique elements. No duplicate elements are allowed.
It may have one null value.
TreeSet Class
// Create an empty TreeSet
Set<String> set = new TreeSet<>();
// Add elements
set.add("Hello");
set.add("World");
// Check if set contains element
boolean contains = set.contains("Hello");
// Remove element
set.remove("Hello");
// Get first and last elements
String first = set.first();
String last = set.last();
// Get size of set
int size = set.size();
// Use iterator
Iterator<String> iter = set.iterator();
while (iter.hasNext()) {
String s = iter.next();
System.out.println(s);
}
// Clear the set
set.clear();
The TreeSet class implements the Set interface using a Tree. It maintains ascending order of elements using their natural ordering or a Comparator provided while creating the TreeSet. Some key points about TreeSet:
It provides slow access time because the elements are stored in a tree.
It maintains ascending order of elements. The elements can be accessed in ascending order.
It allows unique elements. No duplicate elements are allowed.
It may have one null value.
Map Interface
The Map interface provides the functionality of mapping keys to values. The Map interface is extended by the HashMap and TreeMap classes.
HashMap Class
//Creating a HashMap
Map<String, Integer> hmap = new HashMap<>();
hmap.put("One", 1);
hmap.put("Two", 2);
//Creating a TreeMap
Map<String, Integer> tmap = new TreeMap<>();
tmap.put("One", 1);
tmap.put("Two", 2);
The HashMap class implements the Map interface using a hashtable. It uses the hashcode() method to determine the index of a key in the hashtable. Some key points about HashMap:
It provides fast access time because the keys are stored in a hashtable.
It does not maintain any particular order of keys. The keys can be iterated in any order.
It allows one null key and multiple null values.
It does not maintain the insertion order of keys.
TreeMap Class
// Create an empty TreeMap
Map<String, Integer> map = new TreeMap<>();
// Add key-value pairs
map.put("Hello", 1);
map.put("World", 2);
// Get value by key
Integer value = map.get("Hello");
// Check if map contains key
boolean containsKey = map.containsKey("Hello");
// Remove key
map.remove("Hello");
// Get first and last keys
String firstKey = map.firstKey();
String lastKey = map.lastKey();
// Get size of map
int size = map.size();
// Use entrySet() to iterate keys and values
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " - " + value);
}
// Clear the map
map.clear();
The TreeMap class implements the Map interface using a Red-Black tree. It maintains ascending order of keys using their natural ordering or a Comparator provided during the creation of the TreeMap. Some key points about TreeMap:
It provides slower access time because the keys are stored in a tree.
It maintains ascending order of keys. The keys can be iterated in ascending order.
It allows one null key and multiple null values.
It maintains the insertion order of keys.
In summary, the Collection Framework provides a unified architecture to manipulate collections of objects in Java. The interfaces and classes in the Collection Framework help reduce programming effort, increase consistency, and improve performance.