Java Collections Interview Questions and Answers

    11 Votes

Frequently asked best and advanced serialization and Java collections interview questions and answers for freshers, 2-6 year experienced Java Developers with examples.

1) Explain Java Collections framework and its interfaces in hierarchy ?

The Collection is an object that contain group of objects called elements. Collection is the main interface and it is the root interface in the collection hierarchy. Collections Classes are categorized into three based on the interface implemented by them. They are List, Set and Map.

List : The List is an ordered collection which allows duplicates. We can insert values at the end of a list or at a specified index. Main implementations of List interface are

Implemented as a resizable array. Synchronized ArrayList Implemented as a double Linked list.
Fast Iteration and Random Access Fast Random Access. Fast Insertion and deletion.
Grow 50% of its size each time Each time doubles its array size. Add and Remove both End.

Set : The set interface allows only unique values. It won't contain duplicates. Major implementations of set interface are

It's backed by HashMap. It's backed by Hashtable.
It's not ordered. Sorted order.
It allows null object. Not allows null object.
Comparing objects using equals method. uses compareTo() method.
Faster Comparatively slower.

Map : Maps provide a key value pair, where keys are unique. Values are mapped to keys. Maps and Keys are objects. Main implementations of Map interface are

Not synchronized Synchronized Not Synchronized
Better performance. Comparatively less performance because of synchronization. Comparatively less performance because of sorting.
Not sorted Not sorted Sorted
One null key and multiple null values allowed. Won't allow null object.  

2) How hashmap work in Java ?

It works on the principle of Hashing. Hashmap have put(key,value) and get(key) methods for storing and retrieving data. Key value pairs are stored in "Buckets". Each bucket has a unique number allocated to it. When we pass a key-value pair, the internal implementation of hashmap calls hashcode method which returns a hashcode corresponding to the key. Then hashmap look at the buckets whose unique identifier matches with the hashcode of the key value pair. When it finds a match, it stores the data in that bucket. A bucket can have multiple Key value pairs. When we want to retrieve data from the map by passing the key, it will have a look at the hash code of the key to identify the bucket. Once the bucket is identified, it uses  equals() method to retrieve the appropriate key in the bucket.

3) Explain in detail the difference between HashMap, HashTable and Synchronized HashMap ?

HashMapHashTableSynchronized HashMap
Not synchronized Synchronized Synchronized
Better performance. Comparatively less performance because of synchronization. Same ad HashTable, less performance due to synchronization.

4) Difference between Set and List in Java ?

Duplicates Yes No
Order Ordered Depends on implementation
Positional Access Yes No

5) How can Arraylist be synchronized without using Vector ?

Arraylist can be synchronized using

Collection.synchronizedList(List list)

Other collections can be synchronized:  

Collection.synchronizedMap (Map map) and Collection.synchronizedCollection (Collection c)

6) Can you explain about the priority Queue in Java ?

Priority queue uses an unbounded Queue (Which makes sure that no tasks are missed) based on priority heap. Sometimes, it uses large bounded queues to hold the huge no of tasks that an application encounters during runtime. Depending on the type of constructor called at runtime, priority queue elements are ordered based on the natural order or by a Comparator. Null's are not allowed in the priority queue.

7) What are the advantages of using Interface type in collection ?

  • We can switch the implementation without changing the code.
  • It is easy to test our code with testing and mocking frameworks.
  • We can use the most generalized interface for data exchange (enumerator instead of a list, if you only want to iterate over the values).


8) What is the difference between Array and ArrayList ?

Fixed length Size of the Array can be grown based on the need.
Can't use Generics. Can use Generics
Provides length variable which denotes length Provides size() method to calculate size
Can store primitives We can't store primitives

9) Can you explain the difference between fail fast iterator and fail safe iterator ?

Fail fast iterator
: This iterator throws "ConcurrentModificationException" when a thread iterating a collection realizes that the same collection is modified by another thread while under operation. Iterator identifies change in collection is by looking at it's modification count. Ex: HashMap

Fail safe iterator : If we are using fails safe iterator, the above scenario is handled and java doesn't throw the ConcurrentModificationException. To handle this scenario, iterator makes a clone of the collection and works on it. Ex: ConcurrentHashMap

10) Can you explain about concurrent modification exception ?

When two or more threads try to modify an object where concurrent modification is not permitted, java throws concurrent modification exception which is a runtime exception. This exception is thrown by fail fast iterators.

11) what is the difference between iterator and list iterator ?

IteratorList Iterator
Only forward movement is allowed. It can move backwards as well as forward while reading the elements.
While traversing we can't obtain the index at any point. We can obtain the index at any point while traversing
We can only check the availability of the next element We can check availability of previous and next element.
We can't modify element while traversing. Elements can be modified while traversing.

12) Explain the get() and put() logic in hashmap ?

Put (Key,value) 

  • First, check for null in the key. If null, then key value pair will be store in 0'th position. Reason for that is, Hashcode for null is 0.
  • Else, calculate hash code of key by calling hashcode() method
  • Based on the returned hashcode, hashmap implementation goes to the bucket(Stores Key Value pair) who's identifier is matching the returned hashcode. Once bucket is identified, hashmap search the basket for a matching key using equals method. If it finds one, value will be updated
  • If a matching key is not found in the basket, java creates a new Key-Value pair in the basket.

Get (Key)

  • First, use the key to get the hashcode.
  • Go to the basket with matching identifier as hash code.
  • Iterate using equals method to find the matching key in the basket and once key is identified, return value which is stored along with key.

13) What is meant by serialization in Java ?

Java provides serialization to persist a class or a bean's state along with it's property values and state information into a storage. Persisted object can be retreived later and assigned to an object. Interfaces used to implement serialization are Serializable or Externizable Interface.

14) How to avoid Serialization for variable ?

To make it as static or transient.

15) Can you explain about Java design patterns classification ?

Java introduced design patterns to solve design problems. Patterns can be grouped in to three

  • Creational Patterns : This set of design patterns deal with object creation, which create objects based on the situation in which it is created. Ex: Factory Pattern
  • Structural Patterns : Structural Patterns explains the structure formation by combining objects and classes. Ex: Adapter Pattern
  • Behavioral Patterns : Behavioral patterns focus on the interactions between associated objects. Ex: Iterator Pattern

16) How to open a file in append mode ?

BufferedWriter writer = new BufferedWriter( new FileWriter( "ABCD.txt" , true ) );
That extra boolean at the end puts it in append mode.

17) How to open a file in read only mode ?

BufferedReader reader = new BufferedReader(new FileReader("ABCD.txt"));
File file = new File("ABCD.txt");

18) How to create, delete file in Java ?

public void createFile()
  String fileName="NEWFILE.txt";
  File file=newFile(fileName);
public void deleteFile()
    File fileToDelete = newFile("NEWFILE.txt");

19) How to check existence of file in Java ?

File f = new File("NEWFILE.txt");

     System.out.println("File existed");
     System.out.println("File not found!");

Popular Videos


How to improve your Interview, Salary Negotiation, Communication & Presentation Skills.

Got a tip or Question?
Let us know

Related Articles

Java OOPS Interview Questions and Answers
Java Interview Questions
Top Advanced Java Interview Questions and Answers
Java Thread Interview Questions and Answers