Special Offer - Enroll Now and Get 2 Course at ₹25000/- Only Explore Now!

All Courses
Java Collections Interview Questions

Java Collections Interview Questions

August 1st, 2019

Java Collections Interview Questions and Answers

In case you’re searching for Java Collections Interview Questions and Answers for Experienced or Freshers, you are at the correct place. Additionally Our Java Collections Online Training will introduce different types of collections like sets, queues, maps, and lists. Java Collections Online Course has wide coverage of topics like Arraylist class, LinkedList class, list iterator interface, HashSet class, tree set class, map interface, treemap class, hashtable class, sorting, and comparable interface. Java collection framework is used to fetch data, transfer data from one place to another place, hold data, sort entity objects, remove duplicate data, search data, and store the objects in data. Java collection framework knowledge is imperative for android development, health care application development, internet application development, and higher education application development. After the completion of the Java Collections Certification Training, we advise the learners to read the interview question and answers and practice for the interview sessions.

Best Java Collections Interview and Answers

GangBoard Offers Java Collections Interview and Answers.Java collections are the most important concept and one of the core areas of Java. Java collection framework is the fundamental concept or aspect in the Java programming language and is also one of the most prominent parts in Java Collections interview questions and answers. We have researched well and found the top 30 Java collection interview questions.

In this blog of Java collection interview questions, we have covered frequently asked questions based on collection frameworks. Java collection interview questions are the most commonly asked questions by the interviewers for both experienced and freshers. Here I am attempting to put all my possible efforts to provide you good and important Java collection interview questions. So, now let’s get started with the top 30 Java collection interview questions.

Q1)Why collections are introduced in java?

Answer: In order to handle a group of objects previously array is used. But, it has been a drawback of storing only unique data types. To overcome this collection framework have been introduced. It is defined as a single unit to store multiple elements irrespective of its type.

Q2)What are the constituents of the collection framework?

Answer: Collection framework consists of classes and interfaces. All the collection classes are present in  package called java.util.imported as import java.util.collection;.Classes that are present in this package include, stack, hashmap, linked list, etc., Collections are used to store and change the data in object form. Interfaces are Map, Queue list and set.

Q3)How to store data types in the collection framework? (Or) what are autoboxing and auto unboxing?

Answer: Collections don’t accept data types directly like an array. Here the data type has to be converted into an object and stored into the collection. This process is called autoboxing and the reverse of this process is known as auto unboxing. This is introduced in JDK5
Datatype  > (converted)  Object >(stored) > Collection is autoboxing.

Q4)What are the types of interfaces and their implementation?



NOTE:<T> represents these are in generic form.

Q5)What is a wrapper class and how it used in collections?

Answer: The primitive data types like int, boolean, float are not the objects. So they cannot be used in collections, to use these types in collections the wrapper class object is used. wrapper class makes the primitive types to be converted into wrapper class objects. And the int is changed as an integer, char as a character and so on.

Q6)What is list interface and how we use it in collections?

Answer: List interface stores its values in order to allow duplicate values too and extends the collection interface. List interface doesn’t have its own methods and it uses default collection interface methods. The manipulations will be done with the index values.
Classes: stack<t>,linkedlist<t>,arraylist<t>,vector<t>.
Ex: accessspecifier interface  list <t> extends collection<t>.

Q7)what is set interface and how it is used in collections?

Answer: Set is the same as an array. It doesn’t allow duplicate elements and the size of the set grows dynamically. The Set interface implements a collection interface and it increases on insertion. The ordering of the elements is not performed in the set interface and also it does not perform on indexes.
Ex: accessspecifier interface  Set <t> extends collection<t>

Q8)what is queue interface and how it is used?

Answer: The insertion and deletion of the elements follow (FIFO) first in first out order methods in the queue to add(), remove(), peek(), poll(). Insertion from the end of the queue enqueue and removing from the beginning of the queue dequeue.
Ex: accessspecifier interface  Queue <t> extends collection<t>

Q9)How the map interface is used in collections?

Answer: Map interface enables access with key-value phrases and the value is provided when a key is given. The map does not extend the Collection interface and uses its own methods for operating on the data. The map can also allow duplicate elements but the keys are unique.
Package: java.util.map;

Q10)How to retrieve elements from the collection?

Answer: In order to retrieve the elements from the collection there are three interfaces by which the retrieval is possible and they are iterator, list iterator, enumerator interface. These interfaces have their built-in methods to do operations on retrieval. Iterator interface operates only in forward directions. List iterator interface acts as both forward and backward directions whereas enumerator iterator access one after other.

Import java.util.collections;

public class Example

{public static void main(String[]args){

hashtable<Int,Str> ht= new hashtable<int,Str>();


ht.pu(2,”hello”);//adding elements in to table

Enumeration e =(ht.keys()) //retrieving elements using enumeration interface

{Int it=(Int)e.nextElement();//using  methods of enumeration interface

system.out.println((i)+”\t” +ht.get(it));}}

Q11)List out the methods of interface for retrieval?

Answer: Iterator interface has three prominent methods, and they are:

  • Boolean hasnext(): it gives true as the output if any element is left for iteration.
  • element next(): it returns next elements until it is the last element in the list.
  • void remove(): removes element which is currently operating and returns nothing.

Q12)What are the methods present in List Iterator?

Answer: List Iterator has five methods among them three methods are mentioned under the Iterator interface and the rest two methods are listed as follows:

  • Boolean hasprevious(): it gives true as output if any previous element exists.
  • element previous(). Retrieves element previous to the current element.

The list iterator can access the data in both forward and backward directions.

Q13)List out the methods of Enumeration Iterator?

Answer: Enumeration iterator has only two methods, and they are:

  • Boolean hasmoreelements():  it gives the list of the sequence of elements through one by one access.
  • element nextelement(): returns the next element from the data.

Q14)How to add elements into the hash set and properties of the HashSet?

Answer: Hashset represents a set of objects with no guarantee of ordering.it does not allow duplicate values.

Import java.util.*;
Public class Hashset
Public static void main(String[]args)
//creating hashset
Hashset<String> hs=new Hashset<string>();
hs.add(“a”);//add elements to set
hs.add(“b”);//hs is the set object

Q15)what is blocking queue and its properties?

Answer: It is an interface that is used to acquire and access properties of members from the Queue interface. The blocking queue provides concurrency on performing insertion, deletion and retrieval operations. It checks the elements in the queue and promotes the non-emptiness of the queue. Null values are not encouraged in blocking queues and on storing to check the availability then storing happens.
Syntax: public interface blockingqueue<t> extends queue<t>.

Q16)What are properties file and its advantages?

Answer: The Property file stores information that changes regularly and any changes made in property file need not be recompiled which makes ease for managing the application. This file contains the key and value in the form of a string. It is a subclass of hashtable class and properties class enables methods to retrieve data from a properties file. The property value is mainly used to get the property key. Moreover, there are two constructors for the properties class, and they are:

  • properties(): it creates empty properties with no default value.
  • properties(properties defaults): an empty list with a default value provided.

Package: java.util.properties

Import  java.util.properties;
Import java.io.*;
Public class uesesofprop
public static void main(String[] args) {try (InputStream input = new FileInputStream(“path/to/config.properties”))
{usesofprop prop = new usesofprop();//creating obj
system.out.println(“prop.getproperty(“db.username”);//using methods

Q17)what are the uses of generic collections?

Answer: Generic collections are introduced in java 5 edition. It disables typecasting and there is no use of typecasting when it is used in generics. Generic collections are type-safe and checked at compile-time, and it ensures the stability of the program. These collections allow data types to pass as parameters to classes. The Compiler is responsible for checking the compatibility of the types. generics in java are called as templates in c++.
Syntax : class<type>,interface<type>
Type safety: generics allows single type of objects

List l = new ArrayList(); //before generics
List<Integer> l = new ArrayList<Integer>(); //adding generics
l.add(“1”);// it gives the compile time error
Type Casting: no need for type-casting while using generics.
List<String> l = new ArrayList<String>();
String s = l.get(0);  // no need of type casting
Compile-time: Errors are checked at compile time in generics.
List l = new ArrayList(); //before generics
List<Integer> l = new ArrayList<Integer>(); //adding generics
l.add(“1”);// it gives the compile time error

Q18)How to delete duplicate elements from ArrayList?

Answer: There are two major ways of deleting elements from arraylist they are

  • hashset()
  • linkedhashset()

Process of deleting:
Arraylist  (copying)> linked hashset (empty arraylist) >(copy hashset data) >Arraylist.

  • Copy all elements of arraylist into linked hashset
  • Empty array list //clear()
  • Copy from linked hashset to array list again.
/*program to demonstrate removing duplicate elements of array list*/
import java.util.collections;
public class duplication
public static void main(String[] args)
// List with duplicates
ArrayList<Integer> L = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 33, 33, 4, 5,66, 6,66, 7, 8));System.out.println(L);LinkedHashSet<Integer> Set = new LinkedHashSet<>(L);ArrayList<Integer> nodup = new ArrayList<>(Set);System.out.println(nodup);//list without duplicate elements

Q19)How to restrict collection from modifying?

Answer: Restricting collections from modification will make it as read-only. Read only method can be performed by calling unmodifiablecollection() method.

public class readonly {
public static void main(String[] args) {
List<String> List = new ArrayList<String>();List.add(“n”);
List.add(“i”);List<String>unmodifiableList= Collections.unmodifiableList(ist);
unmodifiableList.add(“D”);//This D is not added to the list hence it is unmodified

Q20)Define hashset and its constructors?

Answer: HashSet is defined as a set of elements (objects) which does not guarantee the order of the elements. Duplication of the elements is allowed in HashSet.It is non synchronized and allows unique elements.it is best suitable for searching.
It is available in java.util.hashset class
There are two constructors for hashset they are:

  • hashset(): For defining default hashset this constructor is used.
  • hashset(int capacity):This constructor is to declare the size of the set.however the size is dynamic changes accordingly by the insertion
/* hashset demo*/
import java.util.*;
Public class hashetexample
Public static void main(String[]args)
hashset<integer> l1=new hashset();
iterator<integer> it=l1.iterator();

Q21)what are the reasons for map interface not extending collections interface?

Answer: There are many reasons for not extending collections. They are not compatible with each other.the method exists in a collection called add(element e) is not available in map interface because it requires key and value pairs. considering these differences map interface does not support in extending the collection interface.

Q22)Difference between ArrayList and vector in collections?


ArrayList Vector
Array lists are non synchronized Vector lists are synchronized
In the case  of a single thread, ArrayList can perform faster It is preferable for multithreaded.for single thread it is slow.
ArrayList increases it’s to size by 50%(half) Vector doubles its size dynamically when resized
An array list is added in JDK 1.2 Vector is legacy class

Q23)Difference between hashtable and hashmap?


Hashmap Hashtable
Hash map is non-synchronized Hashtable is synchronized
In case of a single thread, hashmap is fully faster It is faster in multi-threads
Allows the null keys and values Will not allow the null keys
Iteration in hashmap is failed fast. this means iterator will produce an exception occurs only when the concurrent updates are done to the hashmap The enumeration in hashtable is not failed fast. this means even though if concurrent updations are made to the hashtable.

Q24)Difference between set and list?


set List
A set which mainly represents the elements of a collection due to which order of the elements may vary in the set. A list mainly used to display the ordered collection of elements. Even it also preserves list in order to arrange elements in which they are entered.
This will not allow storing duplicate values. The list will also allow duplicate values.
Accessing elements along with their index is not at all possible for sets. In this accessing of elements along with their index can be possible in case of lists.
This mainly will not allow null elements. Lists allow null elements to be stored.

Q25)Difference between Iterator and Enumeration?


Iterator Enumeration
It allows the caller to delete the iteration with remove() method. Its is easy to add and remove elements from the collection.
This is available in the modern class of collection It is available in legacy class.
Enumeration.nextElement() has changed to Iterator.next(). Enumeration.hasMoreElement() changed to Iterator.hasNext().

Q26)What are the major differences between an array to the collection?


  • Both are same in storing objects references.
  • Arrays size is fixed have to define at Initial stages whereas collections size is dynamic.
  • Arrays can store unique data types whereas collections don’t bother about a number of types.
  • Collections use wrapper class objects to store data types in array they store data type directly.

Q27)Difference between the linked list and array list?


ArrayList LinkedList
It is not suitable for manipulation Efficient for manipulation
Suitable for storing and fetching Only for manipulation
It uses Dynamic Array Uses double list
Take less memory overhead because it stores objects only As it stores objects and their address it takes more memory than array list
Can access elements randomly No random access supported

Q28)What does fail-fast mean?

Answer: On the occurrence of a problem this system fails on sudden. this process is mostly seen in iterators. if the user calls an object of the collection.when some other thread is modifying the same .then exception occurs in the process. this process is said to be a fail fast.

Q29)what are ways to synchronize ArrayList?

Answer: There are two major ways to make ArrayList synchronized:

  • By using Collections.synchronizedList() method: this method gives ordered list in return and provides a synchronized list.
  • CopyOnWriteArrayList<E>:Improved term of arraylist with new specifications like add,remove etc.and existed in jdk 1.5.

Q30)Difference between list and map?


List Map
The list allows duplicate values It doesn’t allow duplicates for keys
Allows multiple null values Here null is allowed  once for keys