What is Collection Hierarchy in Java

What is the hierarchy of Collection in Java?

The hierarchy of the complete collection framework comprises four fundamental interfaces such as Collection, List, Set, and Map, as well as two specific interfaces for sorting called SortedSet and SortedMap.

Java contains all interfaces and classes for the collection framework.

Collection Hierarchy In Java
Collection Hierarchy In Java

What are the different types of collections in Java?

There are many interfaces in the Java Collection framework.

  • Set
  • List
  • Queue
  • Classes
  • ArrayList
  • Vector
  • LinkedList
  • PriorityQueue
  • HashSet
  • LinkedHashSet
  • TreeSet

Set Interface

A Set is a Collection in which there are no duplicate elements. It simulates the abstract mathematical set.

Only methods inherited from Collection are included in the Set interface, and it adds the limitation that duplicate elements are not allowed.

The Set may be created as follows:

Set<data-type> se1 = new HashSet<data-type>();  
Set<data-type> se2 = new LinkedHashSet<data-type>();  
Set<data-type> se3 = new TreeSet<data-type>();  

List Interface

In Java, a List interface gives you a way to store an ordered list. It is an interface that is a child of Collection.

It is a list of objects in a certain order that can hold duplicate values.

The list keeps the order in which elements were added, so it can be used to access and add elements based on their position.

Classes ArrayList, LinkedList, Vector, and Stack all implement the List interface.

The list may be created as follows:

List <data-type> listOne= new ArrayList();  
List <data-type> listTwo = new LinkedList();  
List <data-type> listThree = new Vector();  
List <data-type> listFour = new Stack();  

Queue Interface

The Queue interface is part of the java.util package and extends the Collection interface.

It is used to hold elements that are about to be processed in FIFO (First In First Out) order.

First-in, first-out order is kept by the queue interface. It can be described as an ordered list that is used to hold the elements that are about to be processed.

The Queue interface is implemented by classes like PriorityQueue, Deque, and ArrayDeque.

Queue may be created as follows:

Queue<String> que1 = new PriorityQueue();  
Queue<String> que2 = new ArrayDeque();  

ArrayList

The List interface is implemented by the ArrayList class. It keeps the duplicate elements of different data types in a dynamic array.

The ArrayList class keeps the order of how items are added and doesn’t use synchronization.

The ArrayList class lets you access its elements in any order.

Example

import java.util.*;  

   public class TestJavaCollection1{  
   public static void main(String args[]){  
          ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
          list.add("Glenn");//Adding object in arraylist  
          list.add("Jude");  
          list.add("Adones");  
         list.add("Prince");  
            //Traversing list through Iterator  
               Iterator itr=list.iterator();  
     while(itr.hasNext()){  
         System.out.println(itr.next());  
       }  
    }  
}  

Output:

Glenn
Jude
Adones
Prince

Vector

A Vector class implements an array of group objects that can be expanded.

Like an array, it has parts that you can get to with an integer index, just like an array.

But a Vector’s size can grow or shrink as needed to make room for things that are added or taken away after the Vector has been made.

Example:

import java.util.*;  
    public class TestJavaCollection3{  
    public static void main(String args[]){  
       Vector<String> v=new Vector<String>();  
         v.add("Glenn");  
          v.add("Jude");  
           v.add("Adones");  
            v.add("Prince");  
       Iterator<String> itr=v.iterator();  
          while(itr.hasNext()){  
            System.out.println(itr.next());  
        }  
    }  
}  

Output:

Glenn
Jude
Adones
Prince

LinkedList

The LinkedList class is like the ArrayList in that it is a collection that can hold many objects of the same type.

The Collection interface is implemented by LinkedList.

It keeps track of the elements using a double-linked list. It can store the elements that are the same.

It keeps the order of how things are added and is not synchronized.

In LinkedList, it is easy to change things because there is no need to shift.

Example:

import java.util.*;  
     public class TestJavaCollection2{  
     public static void main(String args[]){  
       LinkedList<String> al=new LinkedList<String>();  
         al.add("Glenn");  
          al.add("Jude");  
           al.add("Adones");  
            al.add("Prince");  
     Iterator<String> itr=al.iterator();  
         while(itr.hasNext()){  
           System.out.println(itr.next());  
        }  
    }  
}  

Output:

Glenn
Jude
Adones
Prince

PriorityQueue

The PriorityQueue is used when the objects should be processed based on their priority.

The Queue interface is implemented by the PriorityQueue class.

It keeps track of the elements or objects that need to be processed and how important they are.

PriorityQueue doesn’t let the queue store null values.

Example:

import java.util.*;  
    public class TestJavaCollection5{  
    public static void main(String args[]){  
       PriorityQueue<String> queue=new PriorityQueue<String>();  
          queue.add("Glenn");  
          queue.add("Jude");  
          queue.add("Adones");  
          queue.add("Prince");  
               System.out.println("head:"+queue.element());  
               System.out.println("head:"+queue.peek());  
               System.out.println("iterating the queue elements:");  
        Iterator itr=queue.iterator();  
                      while(itr.hasNext()){  
                          System.out.println(itr.next());  
       }  
           queue.remove();  
           queue.poll();  
               System.out.println("after removing two elements:");  
        Iterator<String> itr2=queue.iterator();  
                     while(itr2.hasNext()){  
               System.out.println(itr2.next());  
           }  
      }  
}  

Output:

head:Adones
head:Adones
iterating the queue elements:
Adones
Jude
Glenn
Prince
after removing two elements:
Jude
Prince

HashSet:

The Java HashSet class is used to make a collection that uses a hash table for storage.

It derives from the AbstractSet class and uses the Set interface.

Important things about the Java HashSet class are: HashSet uses a technique called “hashing” to store the elements.

Example

import java.util.*;  
     public class TestJavaCollection7{  
     public static void main(String args[]){  
      //Creating HashSet and adding elements  
        HashSet<String> set=new HashSet<String>();  
          set.add("Glenn");  
           set.add("Jude");  
            set.add("Adones"); 
             set.add("Prince");  
      //Traversing elements  
               Iterator<String> itr=set.iterator();  
                   while(itr.hasNext()){  
                        System.out.println(itr.next());  
           }  
       }  
}  

Output:

Adones
Prince
Glenn
Jude

LinkedHashSet

The LinkedHashSet is an ordered version of the HashSet that keeps a List with two links between all of its elements.

It’s a class that builds on the HashSet class and uses the Set interface.

Like HashSet, It also contains unique elements. It keeps the order of insertion and allows null elements.

Example:

import java.util.*;  
    public class TestJavaCollection8{  
    public static void main(String args[]){  
       LinkedHashSet<String> set=new LinkedHashSet<String>();  
           set.add("Glenn");  
            set.add("Jude");  
             set.add("Adones");  
              set.add("Prince");  
       Iterator<String> itr=set.iterator();  
           while(itr.hasNext()){  
              System.out.println(itr.next());  
          }  
     }  
}  

Output

Glenn
Jude
Adones
Prince

TreeSet

TreeSet is a class in Java that implements the Set interface and uses a tree to store data.

It comes from the AbstractSet class and implements the NavigableSet interface.

TreeSet also contains unique elements. TreeSet’s access and retrieval time, on the other hand, is quite fast.

The elements in TreeSet are stored in ascending order.

Example

import java.util.*;  
   public class TestJavaCollection9{  
   public static void main(String args[]){  
    //Creating and adding elements  
       TreeSet<String> set=new TreeSet<String>();  
        set.add("Glenn");  
         set.add("Jude");  
          set.add("Adones");  
           set.add("Prince");  
    //traversing elements  
         Iterator<String> itr=set.iterator();  
            while(itr.hasNext()){  
               System.out.println(itr.next());  
        }  
    }  
}  

Output:

Adones
Glenn
Jude
Prince

Methods of Collection Interface in Java

METHODDESCRIPTION
add​(E e)Ensures that this collection contains the specified element (optional operation).
addAll​(Collection<? extends E> c)Adds all the elements in the specified collection to this collection (optional operation).
clear()Removes all the elements from this collection (optional operation).
contains​(Object o)Returns true if this collection contains the specified element.
containsAll​(Collection<?> c)Returns true if this collection contains all the elements in the specified collection.
equals​(Object o)Compares the specified object with this collection for equality.
hashCode()Returns the hash code value for this collection.
isEmpty()Returns true if this collection contains no elements.
iterator()Returns an iterator over the elements in this collection.
parallelStream()Returns a possibly parallel Stream with this collection as its source.
remove​(Object o)Removes a single instance of the specified element from this collection, if it is present (optional operation).
removeAll​(Collection<?> c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
Methods of Collection Interface in Java

Which collection is best in Java?

Most likely, ArrayList, LinkedHashMap, and LinkedHashSet are the best “primary” or “general purpose” implementations with high performance.

Overall, they work better, so you should use them unless you need a special feature that another implementation offers. Most of the time, that special feature is ordering or sorting.

Why collections are used in Java?

Java Collections is a one-stop shop for all data manipulation tasks, like storing data, searching for it, sorting it, adding to it, taking it away, and changing it.

A Java collection framework consists of a single unit, and a Java Collection Framework gives you different Interfaces and Classes to work with.

What is the Collection framework? Java with example

The Java collections framework gives you a set of interfaces and classes that you can use for implementations of the collection interfaces with different data structures and algorithms.

For example, the double-linked list data structure is implemented by the LinkedList class of the collections framework.

What are the two parts of the Java collection framework?

The two main “root” interfaces of Java collection classes are the Collection interface (java.util.Collection) and the Map interface (java.util.Map).

What is the difference between Java collections and Java collections?

In Java, the Collection is an interface, while Collections is a class for doing useful things.

Some of the subinterfaces of the Collection interface are Set, List, and Queue.

A Map interface is also part of the Collections Framework, but it does not inherit from the Collection of Elements.

Is map a collection in Java?

Java includes the map interface. The util package shows how a key is linked to a value. The Collection interface is not a subclass of the Map interface.

Which collection is faster in Java?

If you need to get to elements quickly using an index, you should use ArrayList.

Use HashMap if you need fast access to elements using a key.

Use LinkedList if you need to add or remove items quickly (but it has a very poor seeking performance).

What is ArrayList in Java?

The java.util package has an ArrayList class, which is a resizable array.

Built-in arrays have a size that can’t be changed, but ArrayLists can change their size on the fly.

An ArrayList lets you add and remove elements whenever you need to, which helps you manage your memory.

What is collection API in Java?

A collections API is a unified way to represent and work with collections to be manipulated independently.

This makes it possible to work with collections regardless of how they are represented.

The main benefits of a Collections framework are that it lets APIs that are not related to each other work together and can remove object.

What is HashSet in Java?

HashSet is a Java class that builds on AbstractSet and uses the Set interface.

It’s a very useful tool that lets you keep unique things and get to them at any time. No values are saved more than once.

What is HashMap in Java?

Since Java 1.2, HashMap<K, V> has been part of the Java collection.

The java.util package has this class. It gives the Java Map interface’s basic implementation of iterator.

It stores the data as key-value pairs, which you can get to by using an index of another type (e.g. an Integer)

Collection Interface in Java

The main interface of the Java collections framework is the Collection interface.

This interface is not directly used anywhere. However, it is used by its subinterfaces, such as List, Set, and Queue.

Summary

This article discusses what is the hierarchy of collections in Java.

It also explains the difference between Java collections and Java collections. What is the collection API in Java? 

I hope this lesson has helped you learn a lot. Check out my previous and latest articles for more life-changing tutorials which could help you a lot.


Leave a Comment