What are Collections in Java?

Collections in Java is a utility class present in the java.util.package. For example, It has a method sort() to sort the collection elements according to default sorting order. It has a method min(), and max() to find the minimum and maximum value respectively in the collection elements.

Sounding similar, Java Collection is an interface. For instance, the add(), remove(), clear(), size(), and contains() are the important methods of the Collection interface. It is the root interface for the Collections framework. It is important that we don’t mix them up. Here’s the class hierarchy to make things more clear.

java collection class and interface hierarchy

What is the Java Collections Framework?

A framework is a set of classes and interfaces bundled together in order to implement a new feature. It leverages the benefit of reusability in Object-Oriented Programming. In Java, the Collection framework contains features and methods predefined which we can use in our code using a few simple lines of code!

Java Collections using ArrayList

The ArrayList class is a resizable array, which can be found in java.util package.

The difference between a built-in array and an ArrayList in Java is that the size of an array cannot be modified. While ArrayList is dynamic. It resizes itself automatically when full. The syntax is also slightly different:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsExample {
	public static void main(String[] args) {
		List<Integer> mylist = new ArrayList<Integer> ();
		mylist.add(1);
		mylist.add(4);
		mylist.add(3);
		mylist.add(2);
		System.out.println("mylist before sorting: "+mylist);
		Collections.sort(mylist);
		System.out.println("mylist after sorting : "+mylist);
	}
}

OUTPUT

mylist before sorting: [1, 4, 3, 2]
mylist after sorting : [1, 2, 3, 4]

Notice how on line 13 we sort our Collection using Collections.sort(). It reduces programming effort and eases the workflow of our algorithm.

Java Collections using Liked List

Linked List is almost similar to ArrayList as we saw above.

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class CollectionsExample {
	public static void main(String[] args) {
		List<Integer> mylist = new LinkedList<Integer> ();
		mylist.add(1);
		mylist.add(4);
		mylist.add(3);
		mylist.add(2);
		System.out.println("mylist "+mylist);
		System.out.println("Maximum value in mylist: "+Collections.max(mylist));
	}
}

OUTPUT

mylist [1, 4, 3, 2]
Maximum value in mylist: 4

ArrayList vs. LinkedList in Java

The LinkedList class is a collection that can contain many objects of the same type, just like the ArrayList.

The LinkedList class has all of the same methods as the ArrayList class because they both implement the List interface. This means that you can add items, change items, remove items, and clear the list in the same way.

How ArrayList works?

The ArrayList class has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed.

 ArrayList java collections

How LinkedList works?

The LinkedList stores its items in “containers.” The list has a link to the first container and each container has a link to the next container in the list.

LinkedList java collection

When To Use

It is best to use an ArrayList when:

  • You want to access random items frequently
  • You only need to add or remove elements at the end of the list

It is best to use a LinkedList when:

  • You only use the list by looping through it instead of accessing random items
  • You frequently need to add and remove items from the beginning or middle of the
    list

Enough about Lists. Now let’s take a look at the Queue in Java.

Queue in Java

The queue is an interface in Java. This means that we need to create its object using some class that implements Queue. Here we will be using PriorityQueue to serve our purpose. PriorityQueue stores its elements in ascending order of priority according to ASCII value.

import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Queue;

public class CollectionsExample {
	public static void main(String[] args) {
		Queue myqueue = new PriorityQueue ();
		myqueue.add(7);
		myqueue.add(6);
		myqueue.add(5);
		myqueue.add(9);
		System.out.println("myqueue "+myqueue);
		System.out.println("Maximum value in myqueue: "+Collections.max(myqueue));
	}
}

OUTPUT

myqueue [5, 7, 6, 9]
Maximum value in myqueue: 9

Observing closely one can see that Queue is not showing the elements in ascending order as it should be. Well, PriorityQueue inherits its toString() from java.util.AbstractCollection, which doesn’t know about sort orders. (println uses toString() on all its arguments).

To print in the correct order using the following code:

Integer i;
while ((i = myqueue.poll())!= null) System.out.print(i + " ");

Remember, if we are trying to access a queue element that does not exist, then it will throw a NoSuchElementException.

HashSet

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements the Set interface.

The important points about the Java HashSet class are:

  • Stores the elements by using a mechanism called hashing.
  • Contains unique elements only.
  • Allows null value.
  • Class is non synchronized.
  • HashSet doesn’t maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
  • HashSet is the best approach for search operations.

The property of HashSet to contain unique elements only can be useful to solve many coding problems. For instance, a popular set problem is to remove duplicates. In this case, if we use an array or link list then we have to iterate through the elements and create a parallel list/array as a lookup to be checked every time we visit a new element.

All of this can be skipped just by using HashSet! Just pick all elements and put them in a Java HashSet. Duplicates will automatically get filtered owing to the default property of uniqueness in HashSet.