Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Hi Ninjas! Welcome to a blog on types of collections in Java.
Java is a programming language and computing platform that was first released by Sun Microsystems (now owned by Oracle) in 1995. It is a class-based, object-oriented language based on the concept of classes and objects, and it uses a syntax similar to C and C++.
The article explains the details of types of collections in Java. Let's get started.
A framework in Java is a set of pre-written code and conventions that provide a structure for developing software applications.
Here are some key points to keep in mind when discussing frameworks in Java:
Frameworks provide a common set of conventions and patterns for developers to follow, making it easier to build consistent and maintainable software.
Frameworks provide a set of common functionalities that can be reused across multiple applications, reducing the amount of code that needs to be written from scratch.
Frameworks can help to enforce best practices and design patterns, making it easier for developers to create high-quality software.
In Java, the Collection framework is a set of interfaces and classes that provide a standardized way of representing and manipulating collections of objects. The framework consists of the Collection, List, Set, and Map interfaces, as well as their respective implementations, such as ArrayList, HashSet, and HashMap.
These classes and interfaces provide a wide range of functionality for working with collections of data, including adding and removing elements, searching and sorting elements, and iterating through the elements in a collection.
Why Was the Java Collection Framework Introduced?
Before JDK 1.2, Java used collections like Arrays, Vectors, and Hashtables to store and manage groups of objects. However, these early collection classes had many limitations.
There was no common interface between these data structures, which made it hard to switch between them or reuse code.
The syntax was inconsistent, making the code difficult to read and maintain.
Developers had to write custom logic for basic operations like searching, sorting, or iteration, which increased complexity.
These classes lacked type safety and flexibility, leading to runtime errors.
To solve these issues, the Java Collection Framework was introduced in JDK 1.2. It provided a standard set of interfaces (like List, Set, and Map) along with concrete implementations such as ArrayList, HashSet, and HashMap.
The framework brought uniformity, reusability, and efficiency to Java programming. It also made the collections easier to learn and use by following a consistent architecture.
Advantages of the Collection Framework
The Collection framework in Java provides a wide range of benefits for working with collections of data.
Here are some key advantages of using the Collection framework:
Consistency: The Collection framework provides a consistent set of interfaces and classes for representing and manipulating collections of data, making it easier to work with different types of collections in a consistent and predictable way.
Reusability: The Collection framework provides a set of common functionalities that can be reused across multiple applications, reducing the amount of code that needs to be written from scratch.
Performance: The Collection framework provides optimized implementations of common functionality, such as searching, sorting, and iterating through collections, which can help to improve the performance of the software.
Flexibility: The Collection framework provides a wide range of classes and interfaces for working with different types of collections, such as lists, sets, and maps, making it easy to choose the right type of collection for a specific use case.
Extensibility: The Collection framework is designed to be extensible, making it easy to create new classes and interfaces that extend or adapt the existing functionality.
Iteration: The Collection framework provides the Iterator and the ListIterator interfaces which allows the user to traverse the collection in both the forward and backward direction.
Hierarchy of Collection Framework
Check out the types of collections in Java by Collection framework's hierarchical structure. Each class and interface used by the Collection framework is included in the java.util package.
Methods of Collection Interface
Here are some of the methods defined in the types of collections in Java:
Method
Description
public boolean add(E e)
Adds the specified element to the collection.
public boolean addAll(Collection<? extends E> c)
Adds all of the elements in the specified collection to the current collection.
public void clear()
Removes all of the elements from the collection.
public boolean contains(Object element)
Returns true if the collection contains the specified element.
public boolean containsAll(Collection<?> c)
Returns true if the collection contains all of the elements in the specified collection.
public boolean isEmpty()
Returns true if the collection is empty (contains no elements).
public Iterator iterator()
Returns an iterator over the elements in the collection.
public boolean remove(Object element)
Removes the specified element from the collection.
public boolean removeAll(Collection<?> c)
Removes all of the elements in the specified collection from the current collection.
public boolean retainAll(Collection<?> c)
Retains only the elements in the current collection that are contained in the specified collection.
public int size()
Returns the number of elements in the collection.
public Object[] toArray()
Returns an array containing all of the elements in the collection.
public <T> T[] toArray(T[] a)
Returns an array containing all of the elements in the collection, in the order they are returned by the iterator. The array will be "run out of space" if the collection size is greater than the specified array length.
Iterator interface
The ability to iterate the elements just forward is provided by the iterator interface.
The Iterator interface only has three methods. As follows:
Method
Description
public boolean hasNext()
If there are additional elements in the iterator, it returns true; otherwise, it returns false.
public Object next()
It returns the element and moves the cursor pointer to the next element.
public void remove()
The last elements the iterator returned are removed. It is less used.
Interfaces that Extend the Java Collections Interface
The Java Collection Framework includes several interfaces, each designed to store and manage specific types of data. These interfaces form the foundation of the framework and define the core behaviors for different collection types.
Each interface serves a distinct purpose—whether it's handling lists, sets, queues, or maps—and enables developers to choose the most efficient data structure for their needs.
Iterable Interface
The root interface for all collection classes is the Iterable interface. Since the Collection interface extends the Iterable interface, all of the Collection interface's subclasses also implement the Iterable interface.
There is just one abstract method in it. I.e.,
TIterator<T> iterator()
You can also try this code with Online Java Compiler
The Collection interface is the basic root of the Java collection hierarchy. It defines the basic operations that all collections should have, such as adding and removing elements, checking if the Collection is empty, and obtaining the number of elements in the Collection.
List Interface
The List interface is a sub-interface of Collection and represents an ordered collection of elements. It provides additional operations for working with indexed collections, such as inserting and retrieving elements at specific positions. Classes that implement the List interface include ArrayList and LinkedList.
Syntax
List <data-type> arrl= new ArrayList();
List <data-type> linkl = new LinkedList();
List <data-type> vecl = new Vector();
List <data-type> stackl = new Stack();
You can also try this code with Online Java Compiler
The ArrayList class is a resizable array implementation of the List interface. It provides fast random access and is efficient at inserting and deleting elements at the end of the list.
Example
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
ArrayList<Integer> arrl = new ArrayList<Integer>();
/*appending new element*/
for (int i = 1; i <= 5; i++)
arrl.add(i);
System.out.println(arrl);
// Remove element at index 3
arrl.remove(3);
System.out.println(arrl);
/*Printing elements one by one using a loop*/
for (int i = 0; i < arrl.size(); i++)
System.out.print(arrl.get(i) + " ");
}
}
You can also try this code with Online Java Compiler
The LinkedList class is a Doubly Linked List implementation of the List interface. It provides fast insertion and deletion of elements at any position in the list but is less efficient for random access.
Example
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
LinkedList<String> linkl=new LinkedList<String>();
linkl.add("Welcome");
linkl.add("to");
linkl.add("coding");
linkl.add("ninjas");
Iterator<String> itr=linkl.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
You can also try this code with Online Java Compiler
A subclass of the vector is the stack. It uses the stack Data Structure, or last-in, first-out. The stack offers methods such as boolean push(object o), boolean peek(object o), and boolean push(boolean) that specify its attributes in addition to holding all of the methods of the Vector class.
Example
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) {
Stack<String> stackl = new Stack<String>();
stackl.push("Anjali");
stackl.push("Nitish");
stackl.push("Rahul");
stackl.push("Satish");
stackl.push("Radha");
stackl.pop();
Iterator<String> itr=stackl.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
You can also try this code with Online Java Compiler
In Java, the Queue interface is a subinterface of the Collection interface and represents a collection of elements maintained in a specific order. The order is typically based on an ordering principle such as the insertion order, the element's natural order, or a custom order defined by a Comparator.
Syntax
Queue <T> priQueue = new PriorityQueue<> ();
You can also try this code with Online Java Compiler
The queue data structure has only a very tiny modification in this case. The data structure deque, commonly called a double-ended queue, allows us to add and delete pieces from both ends of the queue.
Syntax
Deque<T> arrDe = new ArrayDeque<> ();
You can also try this code with Online Java Compiler
ArrayDeque is a resizable array implementation of the Deque interface, which can be used as a queue. It provides fast random access and efficiently inserts and deletes elements at both ends of the queue.
Example
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) {
ArrayDeque<Integer> arrDe = new ArrayDeque<Integer>(10);
/*add() method is use to insert*/
arrDe.add(10);
arrDe.add(11);
arrDe.add(12);
arrDe.add(13);
arrDe.add(14);
System.out.println(arrDe);
arrDe.clear();
/*addFirst() method is used to insert the element at head*/
arrDe.addFirst(25);
arrDe.addFirst(35);
// addLast() method is use to insert the element at tail.*/
arrDe.addLast(45);
arrDe.addLast(34);
System.out.println(arrDe);
}
}
You can also try this code with Online Java Compiler
The set interface is a sub-interface of the Collection interface and represents a collection of unique elements. It does not allow duplicate elements and provides additional operations for working with sets such as union, intersection, and set difference.
Syntax
Set<T> hashS = new HashSet<> ();
Set<T> linkHashS = new LinkedHashSet<> ();
You can also try this code with Online Java Compiler
HashSet implements the Set interface that uses a hash table to store the elements. It provides fast containment checking and insertion performance but does not maintain the order of the elements.
Example
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) {
HashSet<String> hashS = new HashSet<String>();
hashS.add("Welcome");
hashS.add("to");
hashS.add("coding");
hashS.add("ninjas");
Iterator<String> itr = hashS.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
You can also try this code with Online Java Compiler
A HashSet and a LinkedHashSet are quite similar. The distinction is that this preserves the element ordering while storing the data with a doubly linked list.
Example
import java.util.*;
public class Main
{
public static void main(String[] args) {
LinkedHashSet<String> linkHashS = new LinkedHashSet<String>();
linkHashS.add("Welcome");
linkHashS.add("to");
linkHashS.add("coding");
linkHashS.add("ninja");
// Traversing elements
Iterator<String> itr = linkHashS.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
You can also try this code with Online Java Compiler
In Java, the SortedSet interface is a sub-interface of the Set interface and represents a collection of unique elements sorted according to their respective order or a specified comparator. It provides additional operations for working with sorted sets, such as finding the first and last elements and sub-sets based on a range of elements.
Syntax
SortedSet<T> treeSet = new TreeSet<> ();
You can also try this code with Online Java Compiler
TreeSet implements the SortedSet interface that uses a Red-Black tree to store the elements. It maintains the natural order of the elements (if the elements implement Comparable) or according to a specified comparator and provides fast access to the first, last, and middle elements.
Example
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) {
TreeSet<String> treeS = new TreeSet<String>();
treeS.add("Welcome");
treeS.add("to");
treeS.add("coding");
treeS.add("ninja");
Iterator<String> itr = treeS.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
You can also try this code with Online Java Compiler
What is the difference between an ArrayList and a LinkedList?
An ArrayList is a resizable array implementation of the List interface. It provides fast random access and is efficient at inserting and deleting elements at the end of the list. A LinkedList is a doubly-linked list implementation of the List interface. It provides fast insertion and deletion of elements at any position in the list but is less efficient for random access.
What is the main difference between a HashMap and a TreeMap?
A HashMap is an implementation of the Map interface that uses a hash table to store key-value pairs. It provides fast lookup and insertion performance but does not maintain the correct order of the elements. A TreeMap is an implementation of the Map interface that uses a Red-Black tree to store key-value pairs. It maintains the elements' natural order and provides fast access to the first, last, and middle elements.
How can I create a thread-safe collection in Java?
You can use classes such as Collections.synchronizedList, Collections.synchronizedSet, and Collections.synchronizedMap to create thread-safe versions of the List, Set, and Map interfaces, respectively. Or you can use classes like Vector and Hashtable, which are thread-safe.
Conclusion
In this article, we have extensively discussed the details of types of collections in Java in which we talk about collections, frameworks, and methods of collection interface.
We hope the blog has helped you enhance your knowledge of types of collections in Java. For more about Java, you can refer to these articles: