Collections In Java

Pranalipardeshi
8 min readMay 20, 2021

--

Source: Edureka

Hoping to get your hands dirty in competitive programming using Java…..Want something like a resizable array🤔 and don’t want to write whole data structure code🤒 and want something midway!!

Source: Pinterest

Then here, we have The Incredible thing in Java🤑….Java’s Collection Framework✨✨.

So Let’s start with Collection and I assure you that you would be able to use the collection in your code, by the end of this blog🙂.

HISTORY

We won’t go into much detail about the history, but the thing we should know about its history is earlier it was called Collection API and after Java 1.2 it was termed as Collection Framework. But after addition to generics, many changes happened in collection classes, which is why people generally call it collection and generics. (It’s Important if you are dealing with multiple versions of java)

Source: Giphy

INTRODUCTION

A collection is a group of objects. In Java, these objects are called elements of the collection. Let’s understand it with a real-time example.

In childhood, you had a kiddy bank. In the kiddy bank, you collected a lot of coins. This kiddy bank is called collection and the coins are nothing but objects.

So we can interpret a collection as a container that stores multiple elements together. A group of objects stored in a collection object is shown in the below figure. In the figure, we are storing 5 objects in a collection object.

Source: https://www.scientecheasy.com/

All collection classes are present in java. util package. Here, util stands for utility. A group of collection classes is called collections framework in java. Here is a simple example java collection object, where we have used the List interface, which we are going to see further in this blog.

// Create a container list of cities (objects or elements)List<String> cities = new ArrayList<String>();// Adding names of cities.
cities.add(“Pune”);
cities.add(“Nagpur”);
cities.add(“Mumbai”);
cities.add(“Delhi”);
cities.add(“Bangalore”);

COLLECTION HIERARCHY IN JAVA

It is required to understand the hierarchy in the collection package. There are different collections and interfaces involved in the collection framework.

Interface: Iterable

The iterable interface is a top interface in the collection framework. It acts as the root interface for all collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of the Collection interface also implement the Iterable interface.

Iterator<T> iterator()

It returns the iterator over the elements of type T

An iterator is an interface that iterates the elements. It is used to traverse the list and modify the elements. Iterator interface has three methods which are mentioned below:

public boolean hasNext()

This method returns true if the iterator has more elements.

public boolean hasNext()

It returns the element and moves the cursor pointer to the next element.

public void remove()

This method removes the last elements returned by the iterator.

Interface: Collection

Collection Interface is the foundation of the Collection framework. Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c), void clear(), etc. these methods are implemented by other collections i.e set, list and queue.

So now let’s move on to the core part of the collection framework. Three interfaces extend the collection framework; those are Set, List, and Queue.

Interface: List

List interface is the child interface of the Collection interface. The list is an ordered collection where we are allowed to have duplicate elements. Elements in the List can be accessed by their position in the list by their index. List interface is implemented classes Array List, Linked List, and Vector.

Let’s check each one!

[1] Array List

We can recall arrays from Java by Array List. Standard arrays in Java are of fixed length, we must know in advance how many elements an array will hold. Basically, it’s an array where we can dynamically grow and shrink its length. In a nutshell, it acts as a dynamic array.

Before moving on to implementation the important thing about ArrayList is that

Array List is not synchronized, i.e it can be called in multiple threads.

Implementation

Array List has three constructors:

ArrayList() : Builds an empty constructor

ArrayList(Collection<? Extends E? c): Builds an array list that is initialized with the elements of collection c.

ArrayList<int capacity>: Builds an ArrayList that has specified initial capacity, which increases as soon as elements are added.

import java.util.*;class ArrayListExample{public static void main(String args[]){ArrayList arrayList = new ArrayList(); // creating array listarrayList.add(“Pune”); // adding elements
arrayList.add(“Delhi”);
Iterator itr = arrayList.iterator();while(itr.hasNext()){
System.out.println(itr.next());}
}
}

In the above program, we are creating an empty ArrayList and then adding elements to it. As you can see we are creating an iterator for ArrayList by using the iterator interface and looping over its elements. Here we have used the add method to add elements to ArrayList. There are other methods too in ArrayList for other operations. You can explore those to have a better grasp of it.

[2] LinkedList

LinkedList provides a LinkedList data structure. We have many types in Linked List data structure such as Singly Linked List, Doubly Linked List, Circular Linked List, etc, wherein here we use singly linked List and doubly linked list to store the elements.

Constructors in LinkedList are almost the same as that of ArrayList.

LinkedList(): Builds an empty linked List

LinkedList(Collection<?extends E>c): Builds Linked List initialized with elements of collection c.

Let’s understand it via implementation.

Implementation

import java.util.*;public class LinkedlistExample{public static void main(String args[]){LinkedList <String> al=new LinkedList <String>(); // creating linked listal.add(“Pune”); // adding elementsal.add(“Nagpur”);al.add(“Delhi”);Iterator <String> itr = al.iterator();while(itr.hasNext()){System.out.println(itr.next());}}}

[3] Vector

Vector is almost similar to that of ArrayList. We can access elements via the index of the vector. But the differences are:

  • Vector is synchronized
  • It has many more methods which aren’t part of the collection framework.

Interface: Queue

Queue interface extends Collection interface and declares the behavior of queue, which is often a FIFO i.e. First-in-First-Out. The basic idea in the queue is that elements are inserted from the front and removed from the end. Which results in the removal of the element which is inserted first.

Methods in the queue have two forms: One which throws an exception if the operation fails and the other which returns a special value.

Source: Edureka

Also, the priority queue implements the Queue interface. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at the queue construction time. The head of this queue is the least element concerning the specified ordering.

Implementation

import java.util.*;public class QueueExample {public static void main(String args[]){Queue<String> pq = new PriorityQueue<>();pq.add(“Pune”);pq.add(“Nagpur”);pq.add(“Delhi”);Iterator iterator = pq.iterator();while (iterator.hasNext()) {System.out.print(iterator.next() + “ “);}}}

Interface: Set

The set interface defines a set. This collection doesn’t allow duplicate elements. Because if you ever try to use add() method for adding duplicate elements. It returns false.

We use this interface to perform mathematical operations which are performed on a mathematical set.

We can see from img[1], the set has an implementation in classes like HashSet, LinkedHashSet, and TreeSet.

Let’s see these by one:

[1] Hash Set

Hash Set class creates a collection that uses a hash table for storage. Hash Table stores information by using a mechanism named Hashing. In hashing, the informational content of a key is used to determine a unique value, which is called hash code. This hash code is then used as an index at which the associated data is stored with the key. Advantage of hashing is that execution of time of add(), contains(), remove() and size() remains constant even for large sets.

Let’s check the basic implementation of the Hash Set.

import java.util.*;class HashsetExample{public static void main(String args[]){HashSet <String> al=new HashSet(); // creating hashSetal.add(“Pune”); // adding elementsal.add(“Mumbai”);al.add(“Delhi”);Iterator <String> itr=al.iterator();while(itr.hasNext()){System.out.println(itr.next());}}}

[2] Linked Hash Set

Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. It contains unique elements like HashSet. Linked HashSet also provides all optional set operations and maintains insertion order.

Let’s check the basic implementation of LinkedHashSet

Implementation

import java.util.*;class LinkedHashsetExample{public static void main(String args[]){LinkedHashSet <String> al=new LinkedHashSet(); // creating linkedhashsetal.add(“Pune”); // adding elementsal.add(“Mumbai”);al.add(“Delhi”);Iterator <String> itr=al.iterator();while(itr.hasNext()){System.out.println(itr.next());}}}

[3] Tree Set

TreeSet class implements the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast which makes TreeSet an excellent choice whenever we want to go with storage of large amounts of information whose access time should be less.

Let’s go through the basic implementation of Tree Set.

Implementation

import java.util.*;class TreeSetExample{public static void main(String args[]){TreeSet <String> al=new TreeSet<String>(); // creating treeSetal.add(“Pune”); // adding elements
al.add(“Mumbai”);
al.add(“Delhi”);
Iterator <String> itr=al.iterator();while(itr.hasNext()){
System.out.println(itr.next());}
}
}

CONCLUSION

Here in this blog, we have discussed the overview of the implementation of interfaces, classes in Collection Framework, implementation of each class, and various other things.

Hence, we can conclude that the collection framework plays a vital role and acts as a savior while solving Competitive coding problem statements. Besides, it also saves our time in development and we can use the interface best as per our requirement and can gain rock-bottom execution time.

Here, it’s not an end, you should definitely explore more about Collection😀😀.

Source: GIPHY

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

--

--

Responses (7)