Java Collection Interview Questions For Freshers

1. What is Collection in Java?

The term collection refers to a group of objects represented as one unit. Classes in the Java collection class hierarchy are divided into two “root” interfaces: Collection (java.util.Collection) and Map (java.util.Map). Terms that you will encounter while learning about the collection in Java:

  • Collection Framework: Java’s Collection Framework defines classes and interfaces for representing groups of objects as a single entity. C++ developers can compare the Collection framework with STL (Standard Template Library) and Container Framework with the Collection Framework if they come from a C++ background.
  • Collection Interface: A class’s interface specifies what it should do, not how. In other words, it is the blueprint for the class. This interface provides the most common methods for all collection objects that are part of the Collection Framework. Alternatively, it represents the individual object as a whole.
  • Collections Class: A member of Collection Framework, it is part of java.util package. The collection object is provided with many utility methods in this class.

2. What is a Framework in Java?

Frameworks are sets of classes and interfaces that provide a ready-made architecture. It is not necessary to define a framework in order to implement new features or classes. As a result, an optimal object-oriented design includes a framework containing a collection of classes that all perform similar tasks. The framework can be used in a variety of ways, such as by calling its methods, extending it, and supplying “callbacks”, listeners, and other implementations. Some of the popular frameworks in java are:

  • Spring
  • Hibernate
  • Struts
  • Google Web Toolkit (GWT)
  • JavaServer Faces (JSF)

3. What is the difference between Array and Collection in Java?

Arrays are a collection of similar-typed variables with a common name in Java. There are some differences between arrays in Java and C/C++. On the other hand, Collections are groups of individual objects that form a single entity known as the collection of objects.

Arrays

Collection

Arrays are fixed in size that is once we create an array we can not increase or decrease based on our requirements.The collection is growable in nature and is based on our requirements. We can increase or decrease of size.
With respect to memory, Arrays are not recommended for use.With respect to memory, collections are recommended for use.
With respect to performance, Arrays are recommended for use.With respect to performance, collections are not recommended for use.
Arrays can hold only homogeneous data types elements.Collection can hold both homogeneous and heterogeneous elements.

For more information, refer to the article – Difference Between Arrays and Collections in Java

4.  What are the various interfaces used in Java Collections Framework?

The collection is known as the root of the collection hierarchy. Collections represent groups of objects known as elements. The java platform does not provide any direct implementation of this interface but the Collection interface is being implemented by List and Set classes.

  • Collection interface
  • List interface
  • Set interface
  • Queue interface
  • Dequeue interface
  • Map interface

5. Explain the hierarchy of the Collection framework in Java.

All classes and interfaces required by the collection framework are contained in the utility package (java. util). Collection frameworks have an interface called an iterable interface, which allows the iterator to iterate over all collections. In addition to this interface, the main collection interface acts as a root for the collection framework. All the collections extend this collection interface thereby extending the properties of the iterator and the methods of this interface. The following figure illustrates the hierarchy of the collection framework. 

Java Collection Hierarchy

6. What are the advantages of the collection Framework?

Advantages of the Collection Framework: Since the lack of a collection framework gave rise to the above set of disadvantages, the following are the advantages of the collection framework. 

  • Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map, all the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have some common set of methods.
     
  • Reduces programming effort: A programmer doesn’t have to worry about the design of the Collection but rather he can focus on its best use in his program. Therefore, the basic concept of Object-oriented programming (i.e.) abstraction has been successfully implemented.
     
  • Increases program speed and quality: Increases performance by providing high-performance implementations of useful data structures and algorithms because in this case, the programmer need not think of the best implementation of a specific data structure. He can simply use the best implementation to drastically boost the performance of his algorithm/program.

7. What is ArrayList in Java? 

ArrayList is a part of the Java collection framework and it is a class of java.util package. It provides us with dynamic arrays in Java. The main advantages of ArrayList are, if we declare an array then it’s needed to mention the size but in ArrayList, it is not needed to mention the size of ArrayList if you want to mention the size then you can do it.

Image of Array List

For more information, refer to the article – ArrayList in Java

8. What is the difference between Collection and Collections?

CollectionCollections
It is an interface.It is a utility class.
It is used to represent a group of individual objects as a single unit.It defines several utility methods that are used to operate on collection.                         
The Collection is an interface that contains a static method since java8. The Interface can also contain abstract and default methods.It contains only static methods.

For more information, refer to the article – Collection vs Collections in Java with Example

9. Difference between ArrayList and LinkedList in the java collection framework?

ArrayList and LinkedList

ArrayList

LinkedList

This class uses a dynamic array to store the elements in it. With the introduction of generics, this class supports the storage of all types of objects.This class uses a doubly linked list to store the elements in it. Similar to the ArrayList, this class also supports the storage of all types of objects.
Manipulating ArrayList takes more time due to the internal implementation. Whenever we remove an element, internally, the array is traversed and the memory bits are shifted.Manipulating LinkedList takes less time compared to ArrayList because, in a doubly-linked list, there is no concept of shifting the memory bits. The list is traversed and the reference link is changed.
This class implements a List interface. Therefore, this acts as a list.This class implements both the List interface and the Deque interface. Therefore, it can act as a list and a deque.
This class works better when the application demands storing the data and accessing it.This class works better when the application demands manipulation of the stored data.

For more information, refer to the article – ArrayList vs LinkedList in Java

10. What is an iterator?

Java’s Collection framework uses iterators to retrieve elements one by one. This iterator is universal since it can be used with any type of Collection object. Using Iterator, we can perform both reading and removing operations. This is an improved version of Enumeration with the addition of removing elements.

When enumerating elements in all Collection framework implemented interfaces, such as Set, List, Queue, Deque, and all implemented classes of Map, an Iterator must be used. The only cursor available for the entire collection framework is the iterator. Using the iterator() method in the Collection interface, you can create an iterator object.

Syntax:

Iterator itr = c.iterator();

Note: Here “c” is any Collection object. itr is of type Iterator interface and refers to “c”.

For more information, refer to the article – Iterators in Java

11. What is the difference between an Iterator and an Enumeration?

A major difference between iterator and enumeration is that iterators have a remove() method while enumerations do not. Thus, using Iterator we can manipulate objects by adding and removing them from collections. Since enumeration can only traverse objects and fetch them, it behaves like a read-only interface.

For more information, refer to the article –  Difference between Iterator and Enumeration

12. What is the difference between List and Set in Java

A major difference between a List and a Set is that a List can contain duplicate elements while a set contains only unique elements. The list is Ordered and maintains the order of the object to which they are added. The set is unordered.

List

Set

The List is an indexed sequence.The Set is a non-indexed sequence.
The list allows duplicate elementsThe set doesn’t allow duplicate elements.
Elements by their position can be accessed.Position access to elements is not allowed.
Multiple null elements can be stored.Null elements can store only once.
List implementations are ArrayList, LinkedList, Vector, StackSet implementations are HashSet, LinkedHashSet.

For more information, refer to the article – Difference Between List and Set in Java

13. What are the best practices for Java Collections Framework?

Following are some of the best practices while using Java Collections:

  • Programs should be written as interfaces, not implementations, so we can modify the implementation later.
  • Whenever possible, use Generics to ensure type safety and avoid ClassCastExceptions.
  • Choosing the appropriate type of collection based on the need. For example, if the size is fixed, we might want to use an Array over an ArrayList. When iterating over the Map, we should use LinkedHashMap. Set is the best way to avoid duplicates.
  • Use immutable classes provided by JDK as keys in Map to avoid implementation of hashCode() and equals().
  • In order to increase the readability of the code, we should use isEmpty() instead of finding the size of the collection and comparing it to zero.
  • Rather than writing your own implementation, use the Collections utility class to get read-only, Synchronized, or empty collections instead. It enhances code reuse while resulting in greater stability.

14. What is a priority queue in Java?

PriorityQueues are used to process objects according to their priority. Queues follow the First-In-First-Out algorithm, but sometimes the elements of the queue need to be processed according to their priority, which is where PriorityQueue comes into play. Priority queues are based on priority heaps.

The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.  

Priority Queues in Java

Declaration:

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
where E is the type of elements held in this queue

The class implements Serializable, Iterable<E>, Collection<E>, and Queue<E> interfaces.

15. What is the difference between List, set, and map in java?

List

Set

Map

The list interface allows duplicate elements

The set does not allow duplicate elements.

The map does not allow duplicate elements

The list maintains insertion order.

The set does not maintain any insertion order. 

The map also does not maintain any insertion order. 

We can add any number of null values.

But in the set almost only one null value.

The map allows a single null key at most and any number of null values.

The list implementation classes are Array List and LinkedList.

Set implementation classes are HashSet, LinkedHashSet, and TreeSet. 

Map implementation classes are HashMap, HashTable, TreeMap, ConcurrentHashMap, and LinkedHashMap.

For more information, refer to the article – Difference between List, Set, and Map in Java

16. What is the difference between Queue and Stack?

Stack

Queue

Stacks works on the LIFO principle, which means that the element inserted at the last will be the first element that will be taken out.Queues work on the FIFO principle, which means that the element inserted first will be the first element that will be taken out.
In stacks, insertion, and deletions take place only from the top.In queues, insertion occurs at the rear of the list and deletion takes place from the front of the list.
Insert operation is called push operation.Insert operation is called enqueue operation.
Delete operation is called pop operation.Delete operation is called dequeue operation.
The top of a stack always points to the last element in the list, which is the only pointer used to access the list.Two pointers are maintained for accessing queues. The front pointer points to the first inserted element, and the rear pointer points to the last inserted element.

17. What is BlockingQueue in Java?

The BlockingQueue interface in Java is added in Java 1.5 along with various other concurrent Utility classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList, etc. The BlockingQueue interface supports flow control (in addition to queue) by introducing blocking if either BlockingQueue is full or empty.

A thread trying to enqueue an element in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more elements or clearing the queue completely. Similarly, it blocks a thread trying to delete from an empty queue until some other threads insert an item. BlockingQueue does not accept a null value. If we try to enqueue the null item, then it throws NullPointerException.

Usage of BlockingQueue 

Blocking Queue in Java

The Hierarchy of BlockingQueue

Hierarchy of Blocking Queue in Java

Declaration:

public interface BlockingQueue<E> extends Queue<E>

Here, E is the type of elements stored in the Collection.

For more information, refer to the article – BlockingQueue Interface in Java

18. What is the hashCode()?

Image to demonstrate Java Hash Code

hashCode() method returns the hashcode value as an Integer. It is defined in the Java Object class which computes the hash values of given input objects. Hashcode value is mostly used in hashing-based collections like HashMap, HashSet, HashTable….etc. This method must be overridden in every class which overrides the equals() method.

Syntax :

public int hashCode()
// This method returns the hash code value 
// for the object on which this method is invoked.

For more information, refer to the article – equals() and hashCode() methods in Java

19. Distinguish between ArrayList and Vector in the Java Collection Framework.

In collection interviews, this question is frequently asked; however, Vector is synchronized whereas ArrayList is not. ArrayList is faster than Vector. ArrayList’s Array size is increased by 50% when needed, while Vector’s capacity is doubled whenever it is needed.

Array List vs Vector in java

ArrayList

Vector

ArrayList is not SynchronizedThe vector is synchronized.
The size of ArrayList is incremented up to 50% of the current array size if the number of elements exceeds its capacity.The size of ArrayList is incremented up to 100% of the current array size if the number of elements exceeds its capacity.
ArrayList is fast because it is non-Synchronized.Vector is slower because it’s synchronized.
The iterator interface is used to traverse the elementsAn iterator interface or Enumeration can be used to traverse the vector.

For more information, refer to the article – Vector vs ArrayList in Java

20. Differentiate between Iterator and ListIterator.

Iterator

ListIterator

Can traverse elements present in Collection only in the forward direction.Can traverse elements present in the Collection both in the forward and backward directions.
Helps to traverse Map, List, and Set.Can only traverse List and not the other two.
Indexes cannot be obtained by using Iterator.It has methods like nextIndex() and previousIndex() to obtain indexes of elements at any time while traversing the List.
Cannot modify or replace elements present in the CollectionWe can modify or replace elements with the help of set(E e)

For more information, refer to the article – Difference Between an Iterator and ListIterator

21. What is the difference between an Iterator and an Enumeration?

Iterator: It is a universal iterator as we can apply it to any Collection object. By using an Iterator, we can perform both read and remove operations. 

Syntax: 

// Here "c" is any Collection object. itr is of
// type Iterator interface and refers to "c"
Iterator itr = c.iterator();

Enumeration: Enumeration (or enum) is a user-defined data type. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. 

Syntax: 

// A simple enum example where enum is declared 
// outside any class (Note enum keyword instead of 
// class keyword) 
enum Color 
{ 
    RED, GREEN, BLUE; 
}

Iterator

Enumeration

The iterator is a universal cursor as it is applicable to all the collection classes.Enumeration is not a universal cursor as it applies only to legacy classes.
The iterator has the remove() method.Enumeration does not have the remove() method.
The iterator can do modifications (e.g using the remove() method which removes the element from the Collection during traversal).The enumeration interface acts as a read-only interface, one can not do any modifications to the Collection while traversing the elements of the Collection.
Iterator is not a legacy interface. Iterator can be used for the traversal of HashMap, LinkedList, ArrayList, HashSet, TreeMap, and TreeSet.Enumeration is a legacy interface that is used for traversing Vector, and Hashtable.

For more information, refer to the article – Difference between Iterator and Enumeration 

22. What are the features of Java Hashmap?

HashMap is similar to HashTable, but it is unsynchronized. It allows us to store the null keys as well, but there should be only one null key object and there can be any number of null values.  This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util. HashMap package or its superclass.
 

HashMap in Java

 Syntax: 

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable

Parameters: It takes two parameters namely as follows:

  • The type of keys maintained by this map (K)
  • The type of mapped values (V)

For more information, refer to the article – HashMap in Java with Examples

23. What are Collection Interfaces?

The Collection interface is a member of the Java Collections Framework. It is a part of java.util package. It is one of the root interfaces of the Collection Hierarchy. The Collection interface is not directly implemented by any class. However, it is implemented indirectly via its subtypes or subinterfaces like List, Queue, and Set. 

For Example, the HashSet class implements the Set interface which is a subinterface of the Collection interface. If a collection implementation doesn’t implement a particular operation, it should define the corresponding method to throw UnsupportedOperationException.

The Hierarchy of Collection:

Collection Interface in Java

24. Explain the list interface.

Class Interface in Java

In Java, the List interface allows the user to store an ordered collection of objects. The list is the child interface of Collection. In Collection, a list is an ordered collection of objects which can have duplicate values. Since List preserves the insertion order, it allows positional access and insertion, which also allows duplicate values.

Syntax:

public interface List<E> extends Collection<E> ;

This list interface is implemented by various classes like ArrayList, Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list object with any of these classes. 

Example: 

List <T> al = new ArrayList<> (); 
List <T> ll = new LinkedList<> (); 
List <T> v = new Vector<> (); 

Where T is the type of the object 

Array List in Java

The classes which implement the List interface are as follows:

  • ArrayList
  • LinkedList
  • Vector
  • Stack

25. Write a program to convert a given array into a collection with the asList() method.

To convert array-based data into Collection based we can use java.util.Arrays class. This class provides a static method asList(T… a) that converts the array into a Collection.

Java
// Convert an Array into Collection in Java
// import java util library
import java.util.*;

// class for writing logic of the problem
public class ArrayToCollection {
    public static void main(String args[])
    {
        // array input
        String students[] = { "Kamlesh", "Abhay",
                              "Abhishek", "Shivansh" };

        // printing input elements for comparison
        System.out.println("Array input: "
                           + Arrays.toString(students));

        // converting array into Collection
        // with asList() function
        List studentList = Arrays.asList(students);

        // print converted elements
        System.out.println("Converted elements: "
                           + studentList);
    }
}

Output
Array input: [Kamlesh, Abhay, Abhishek, Shivansh]
Converted elements: [Kamlesh, Abhay, Abhishek, Shivansh]



26. Differentiate between HashSet and HashMap

HashSet 

HashMap 

HashSet implements the Set interface HashMap implements the Map interface 
No Duplicates are allowed Yes duplicates values are allowed but no duplicate key is allowed 
Dummy values are allowed in HashSet.No Dummy values are allowed in HashMap.
A single Object is required during an add operation                                                 2 Objects are required during an add operation
Speed is comparatively slower than HashMapSpeed is comparatively faster than HashSet because of hashing technique has been used here.
Have a single null value Single null key and any number of null values
Add() method is used for the insertionThe put () method is used for insertion.

For more information, refer to the article – Difference between HashMap and HashSet

27. Differentiate between HashSet and HashTable.

HashSet

HashTable

HashSet allows NULL ElementsHashTable does not allow NULL Elements.

Objects that you insert in HashSet are not guaranteed to be inserted in the same order. Objects are inserted based on their hash code. LinkedHashSet can be used to maintain order.

HashTable does not maintain insertion order.
HashSet is not Synchronized but it can be synchronized externally.HashTable is Synchronized.
add() method is used to insert into HashSet put() method is used to insert into HashTable

28. What is the default size of the load factor in the hashing-based collection?

As the Load Factor increases, the capacity increases so that the operational complexity of the HashMap remains O(1) if the ratio of the current element to the initial capacity crosses the threshold. The meaning of operational complexity of O(1) means the retrieval and insertion operations take constant time. The default load factor size is 0.75. The default capacity is calculated by multiplying the initial capacity by the load factor.

For more information, refer to the article – Load Factor in HashMap in Java with Examples

Java Collections Interview Questions and Answers

Java Collection Framework was introduced in JDK 1.2 which contains all the collection classes and interfaces. Java Collection is a framework that provides a mechanism to store and manipulate the collection of objects. It allows developers to access prepackaged data structures and algorithms for manipulating data. 

Here, we’ve covered the 50+ Java Collections Interview Questions and Answers tailored for both Fresher and experienced professionals, which cover everything from basic to advanced Java collection concepts such as navigation collection, WeakHashMap, streams Lambdas, etc.

Java Collections Interview Questions

Whether you are a fresher or an experienced Java developer, these Java Collections Interview Questions give you all the confidence you need to ace your next Java interview.

Table of Content

  • Java Collection Interview Questions For Freshers
  • Java Collection Interview Questions For Experienced

We have divided the 50 questions into two parts: Experienced and Freshers. Let’s begin with the questions for Freshers.

Similar Reads

Java Collection Interview Questions For Freshers

1. What is Collection in Java?...

Java Collection Interview Questions For Experienced

29. What is the difference between Comparable and Comparator in Java?...

Conclusion

Java Collections is important to understand for Java developers or programmers because Java is widely used in various industries. It’s important for developers to have a solid understanding of core concepts of Java Collections. Java is one of the most widely used languages in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, etc. To get into these companies or any other IT companies, you need to master these mostly asked Java Collections interview questions in order to crack their Java-based online assessment and technical interview....

Java Collections Interview Questions – FAQs

What are collections in Java interview questions?...

Contact Us