Java Collections Interview Questions & Answers

1) What is the Java Collection framework?

Collection Framework is a combination of classes and interface, which is used to store and manipulate the data in the form of objects. It provides various classes such as ArrayList, Vector, Stack, and HashSet, etc. and interfaces such as List, Queue, Set, etc.

2) What are the advantages of the Collection Framework in Java?

– Reduced programming effort due to ready to use code

– Increased performance because of high-performance implementations of data structures and algorithms

– Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth

– Easy to learn APIs by learning only some top level interfaces and supported operations

3) What are the main differences between array and collection?

– Arrays are always of fixed size, i.e., a user can not increase or decrease the length of the array at runtime, but In Collection, size can be changed dynamically as per need.
– Arrays can only store homogeneous or similar type objects, but in Collection, heterogeneous objects can be stored.
– Arrays does not have any methods for sorting, searching, etc. but Collection includes readymade methods to use.

4) Explain various interfaces used in Collection framework?

– Collection Interface: java.util.Collection is the root of the Java Collection framework and most of the collections in Java are inherited from this interface.
– List Interface: java.util.List is an extended form of an array that contains ordered elements and may include duplicates. The List interface is implemented by various classes such as ArrayList, LinkedList, Vector, etc.
– Set Interface: java.util.Set refers to a collection class that cannot contain duplicate elements.
The Set interface is implemented by various classes such as HashSet, TreeSetand LinkedHashSet.
– Queue Interface: java.util.Queue in Java follows a FIFO approach i.e. it orders the elements in First In First Out manner.
– Map Interface: java.util.Map is a two-dimensional data structure in Java that is used to store the data in the form of a Key-Value pair.

5) Why Map interface does not extend Collection interface?

Both are incompatible. Collection has a method add(Object o) but Map can not have such method because it need key-value pair. Map supports keySet and valueSet but Collection classes does not have such views.

6) What is the primary difference between List and Set?

– Set holds unique elements whereas List can have duplicate items.
– Set is an unordered collection whereas List is the ordered one.
– List preserves the order of the object addition but Set doesn’t preserve any order.

7) What is the difference between Iterator and ListIterator?

– The List can contain duplicate elements whereas Set includes unique items.
– The List is an ordered collection which maintains the insertion order whereas Set is an unordered collection which does not preserve the insertion order.
– The List interface contains a single legacy class which is Vector class whereas Set interface does not have any legacy class.
– The List interface can allow n number of null values whereas Set interface only allows a single null value.

8) What is the difference between fail-fast and fail-safe Iterators?

Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on underlying collection. They are called fail-fast because they try to immediately throw Exception when they encounter failure. On the other hand fail-safe Iterators works on copy of collection instead of original collection.

9) What is the difference between Iterator and Enumeration?

– The Iterator is fail-fast. Enumeration is not fail-fast.
– The Iterator is slower than Enumeration. Enumeration is faster than Iterator.
– The Iterator can perform remove operation while traversing the collection. The Enumeration can
perform only traverse operation on the collection.

10) What is the difference between HashSet and TreeSet?

– HashSet maintains no order whereas TreeSet maintains ascending order.
– HashSet performs faster than TreeSet.
– HashSet is backed by HashMap whereas TreeSet is backed by TreeMap.

11) What is the difference between Set and Map?

– Set contains values only whereas Map contains key and values both.
– Set contains unique values whereas Map can contain unique Keys with duplicate values.
– Set holds a single number of null value whereas Map can include a single null key with n number of null values.

12) What is the difference between HashSet and HashMap?

– HashSet contains only values whereas HashMap includes the entry (key, value).
– HashSet can be iterated, but HashMap needs to convert into Set to be iterated.
– HashSet implements Set interface whereas HashMap implements the Map interface
– HashSet cannot have any duplicate value whereas HashMap can contain duplicate values with unique keys.
– HashSet contains only single number of null value whereas HashMap can
hold a single null key with n number of null values.

13) What is the difference between HashMap and TreeMap?

– HashMap maintains no order, but TreeMap maintains ascending order.
– HashMap is implemented by hash table whereas TreeMap is implemented by a Tree structure.
– HashMap can be sorted by Key or value whereas TreeMap can be sorted by Key.
– HashMap may contain a null key with multiple null values whereas TreeMap cannot hold a null key but can have multiple null values.

14) What is the difference between HashMap and Hashtable?

– HashMap is not synchronized but Hashtable is synchronized.
– HashMap can contain one null key and multiple null values but Hashtable cannot contain any null key or null value.
– HashMap is not thread-safe but Hashtable is thread safe.

15) How to synchronize List, Set and Map elements?

public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

16) What is the advantage of the generic collection?

– If we use the generic class, we don’t need typecasting.
– It is type-safe and checked at compile time.
– Generic confirms the stability of the code by making it bug detectable at compile time.

17) What is the difference between Array and ArrayList?

– Array is of fixed size and cannot be resized but the size of ArrayList can be changed dynamically.
– Arrays can store primitive data type as well as objects. ArrayList cannot store primitive data types, it can only store objects.

18) How to convert ArrayList to Array and Array to ArrayList?

We can convert an Array to ArrayList by using the asList() method of Arrays class.
Arrays.asList(item)

We can convert an ArrayList to Array using toArray() method of the ArrayList class.
List.toArray(new String[List.size()])

19) How to remove duplicates from ArrayList?

– By using HashSet we can remove the duplicate element from the ArrayList, but it will not preserve the insertion order.

public class RemoveDuplicatesFromList {

public static void main(String[]args){
Set<String> set = new HashSet<String>();
List<String> inputList = new ArrayList<String>();
inputList.add("Java");
inputList.add("C#");
inputList.add("Python");
inputList.add("Java");
set.addAll(inputList);
List<String> newList = new ArrayList<String>();
newList.addAll(set);
System.out.println(newList);
}

}

 

20) How will you reverse an List?

ArrayList can be reversed using the reverse() method of the Collections class.

public void reverseList(){
List<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add("C#");
languages.add("Python");
Collections.reverse(languages);
System.out.println(languages);
}

 

21) What do you understand by LinkedList in Java? How many types of LinkedList does Java support?

LinkedList in Java is a data structure that contains a sequence of links. Here each link contains a connection to the next link.

Java LinkedList class uses two types of LinkedList to store the elements:
– Singly Linked List: In a singly LinkedList, each node in this list stores the data of the node and a pointer or reference to the next node in the list.
– Doubly Linked List: In a doubly LinkedList, it has two references, one to the next node and another to the previous node.

22) What is a Vector in Java?

Vectors are similar to arrays, where the elements of the vector object can be accessed via an index into the vector. Vector implements a dynamic array. Also, the vector is not limited to a specific size, it can shrink or grow automatically whenever required.
It is similar to ArrayList, but with two differences :
– Vector is synchronized.
– Vector contains many legacy methods that are not part of the collections framework.

23) Can you add a null element into a TreeSet or HashSet?

In HashSet, only one null element can be added but in TreeSet it can’t be added. So, in case you try to add null elements to a TreeSet, it will throw a NullPointerException.

24) What is LinkedHashSet in Java Collections Framework?

A java.util.LinkedHashSet is a subclass of the HashSet class and implements the Set interface.
It is an ordered version of HashSet which maintains a doubly-linked List across all elements contained within.
It preserves the insertion order and contains only unique elements like its parent class.

25) What is the ConcurrentHashMap in Java?

ConcurrentHashMap is a Java class that implements ConcurrentMap as well as Serializable interfaces.
This class is the enhanced version of HashMap as it doesn’t perform well in the multithreaded environment.
It has a higher performance rate compared to the HashMap.

26) What is the difference between Collection and Collections?

The Collection is an interface while Collections is a java class, both are present in java.util package and part of the java collections framework.

27) When to use ArrayList and LinkedList in the application?

ArrayList has a constant time search operation O(1). Hence, ArrayList is preferred when there are more get() or search operation.
Insertion, Deletion operations take constant time O(1) for LinkedList. Hence, LinkedList is preferred when there are more insertions or deletions involved in the application.

28) Explain the emptySet() method in the Collections framework?

The Collections.emptySet() is used to return the empty immutable Set while removing the null elements.
The set returned by this method is serializable. Below is the method declaration of emptySet():
public static final <T> Set<T> emptySet()

29) How HashMap works in Java?

HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode() and equals() method in put and get methods.

When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there is an already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and stores this key-value Entry.

When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return its value.

30) Which collection classes provide random access of its elements?

ArrayList, HashMap, TreeMap, Hashtable, and Vector classes provide random access to its elements.

31) Write a Java program to find frequency of each character in a string

class DuplicateCharactersInString
{
static void duplicateCharCount(String inputString)
{
//Creating a HashMap containing char as key and it's occurrences as value
HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();

//Converting given string to char array
char[] strArray = inputString.toCharArray();

//checking each char of strArray
for (char c : strArray)
{
if(charCountMap.containsKey(c))
{
//If char is present in charCountMap, incrementing it's count by 1
charCountMap.put(c, charCountMap.get(c)+1);
}
else
{
//If char is not present in charCountMap,
//putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}

//Getting a Set containing all keys of charCountMap
Set<Character> charsInString = charCountMap.keySet();

//Iterating through Set 'charsInString'
for (Character ch : charsInString)
{
if(charCountMap.get(ch) > 1)
{
//If any char has a count of more than 1, printing it's count
System.out.println(ch +" : "+ charCountMap.get(ch));
}
}
}

 

32) Write a Java program to find longest substring without repeating characters.

 

public class FindLongestSubStringWithoutRepeatingChars {

static void longestSubstring(String inputString)
{
//Remove any whitespaces from the string
String strInput = inputString.replaceAll("\\s", "");
//Convert inputString to charArray
char[] charArray = strInput.toCharArray();
String longestSubstring = null;
int longestSubstringLength = 0;

//Creating LinkedHashMap with characters as keys and their position as values.
LinkedHashMap<Character, Integer> charPosMap = new LinkedHashMap<Character, Integer>();

//Iterating through charArray
for (int i = 0; i < charArray.length; i++)
{
char ch = charArray[i];
//If ch is not present in charPosMap, adding ch into charPosMap along with its position
if(!charPosMap.containsKey(ch))
{
charPosMap.put(ch, i);
}

//If ch is already present in charPosMap, reposioning the cursor i to the position
//of ch and clearing the charPosMap
else
{
i = charPosMap.get(ch);
charPosMap.clear();
}
//Updating longestSubstring and longestSubstringLength
if(charPosMap.size() > longestSubstringLength)
{
longestSubstringLength = charPosMap.size();
longestSubstring = charPosMap.keySet().toString();
}
}
System.out.println("Input String : "+strInput);
System.out.println("The longest substring : "+longestSubstring);
System.out.println("The longest Substring Length : "+longestSubstringLength);
}

public static void main(String[] args)
{
longestSubstring("Advanced Java Interview Questions");
}
}

 

33) Write a Java program to find the most repeated word in a Text file

public class FindMostRepeatedWordInFile {

public static void main(String[] args)
{
//Creating wordCountMap which holds words as keys and their occurrences as values
HashMap<String, Integer> wordCountMap = new HashMap<String, Integer>();
BufferedReader reader = null;
try
{
//Creating BufferedReader object
reader = new BufferedReader(new FileReader("src/main/resources/File.txt"));

//Reading the first line into currentLine
String currentLine = reader.readLine();
while (currentLine != null)
{
//splitting the currentLine into words
String[] words = currentLine.toLowerCase().split(" ");

//Iterating each word
for (String word : words)
{
//if word is already present in wordCountMap, updating its count
if(wordCountMap.containsKey(word))
{
wordCountMap.put(word, wordCountMap.get(word)+1);
}
//otherwise inserting the word as key and 1 as its value
else
{
wordCountMap.put(word, 1);
}
}
//Reading next line into currentLine
currentLine = reader.readLine();
}
//Getting the most repeated word and its occurrence
String mostRepeatedWord = null;
int count = 0;
Set<Map.Entry<String, Integer>> entrySet = wordCountMap.entrySet();
for (Map.Entry<String, Integer> entry : entrySet)
{
if(entry.getValue() > count)
{
mostRepeatedWord = entry.getKey();
count = entry.getValue();
}
}
System.out.println("The most repeated word in input file is : "+mostRepeatedWord);
System.out.println("Number Of Occurrences : "+count);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
//Closing the reader
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}

 

34) Write a Java program to sort an ArrayList.

public class SortArrayList {

public static void main(String[] args){

List<String> languageList = new ArrayList<String>();
languageList.add("Java");
languageList.add("C#");
languageList.add("Python");
languageList.add("Ruby");

System.out.println("List before sorting: "+languageList);
Collections.sort(languageList);
System.out.println("List after sorting: "+languageList);
}
}

 

35) How do you convert an ArrayList to Array?

Using toArray() method of ArrayList class. toArray() method returns an array containing
all elements of the ArrayList.

class convertToArray{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add("JAVA");
list.add("J2EE");
list.add("JSP");
list.add("SERVLETS");
list.add("STRUTS");
System.out.println(list);

//getting an array containing all elements of the list.
Object[] array = list.toArray();

//Printing the elements of the returned array.
for (Object object : array)
{
System.out.println(object);
}
}
}

 

36) Write a Java program to find frequency of all digits in a number.

public class FindFrequencyOfDigits {

public static void main(String[] args)
{
int inputNumber = 23432;

HashMap<Integer, Integer> digitCountMap = new HashMap<Integer, Integer>();

while (inputNumber != 0)
{
//Get the lastDigit of inputNumber
int lastDigit = inputNumber % 10;
if(digitCountMap.containsKey(lastDigit))
{
//If lastDigit is already present in the map, incrementing its frequency by 1
digitCountMap.put(lastDigit, digitCountMap.get(lastDigit)+1);
}
else
{
//If lastDigit is not present in the map, inserting lastDigit into map with 1 as its value
digitCountMap.put(lastDigit, 1);
}
//Removing the lastDigit from inputNumber
inputNumber = inputNumber / 10;
}
//Printing digits and their frequency
System.out.println("Digits : Frequency");
Set<Integer> keys = digitCountMap.keySet();
for (Integer key : keys)
{
System.out.println(" "+key+" : "+digitCountMap.get(key));
}
}
}

 

37) Write a Java program to find the most frequent element in an array.

public class FindMostFrequentElementInArray {

static void getMostFrequentElement(int inputArray[])
{
//Creating HashMap object with elements as keys and their occurrences as values
HashMap<Integer, Integer> elementCountMap = new HashMap<Integer, Integer>();
//Inserting all the elements of inputArray into elementCountMap
for (int i : inputArray)
{
if (elementCountMap.containsKey(i))
{
//If an element is present, incrementing its count by 1
elementCountMap.put(i, elementCountMap.get(i)+1);
}
else
{
//If an element is not present, put that element with 1 as its value
elementCountMap.put(i, 1);
}
}
int element = 0;
int frequency = 1;
//Iterating through elementCountMap to get the most frequent element and its frequency
Set<Map.Entry<Integer, Integer>> entrySet = elementCountMap.entrySet();
for (Map.Entry<Integer, Integer> entry : entrySet)
{
if(entry.getValue() > frequency)
{
element = entry.getKey();
frequency = entry.getValue();
}
}
//Printing the most frequent element in array and its frequency
if(frequency > 1)
{
System.out.println("Input Array : "+Arrays.toString(inputArray));
System.out.println("The most frequent element : "+element);
System.out.println("Its frequency : "+frequency);
}
else
{
System.out.println("Input Array : "+ Arrays.toString(inputArray));
System.out.println("No frequent element. All elements are unique.");
}
}

public static void main(String[] args)
{
getMostFrequentElement(new int[]{4, 6, 8, 7, 4, 7, 6,7});
}
}

 

38) Write a Java program to find the missing number in the array.

public class FindMissingNumberInArray {

static int sumOfNumbers(int n)
{
int sum = (n * (n+1))/ 2;
return sum;
}

//Method to calculate sum of all elements of array
static int sumOfElements(int[] array)
{
int sum = 0;
for (int i = 0; i < array.length; i++)
{
sum = sum + array[i];
}
return sum;
}

public static void main(String[] args)
{
int n = 8;
int[] a = {1, 4, 5, 3, 7, 8, 6};
int sumOfNumbers = sumOfNumbers(n);
int sumOfElements = sumOfElements(a);
int missingNumber = sumOfNumbers - sumOfElements;
System.out.println("Missing Number is = "+missingNumber);
}
}

 

39) Write a Java program to find common elements in 2 Arrays.

use reatinAll() method of HashSet to retain only common elements from the two sets.

public class FindCommonElementsInTwoArrays {
public static void main(String[] args){
Integer[] i1 = {1, 2, 3, 4, 5, 4};
Integer[] i2 = {3, 4, 5, 6, 7, 4};
HashSet<Integer> set1 = new HashSet<Integer>(Arrays.asList(i1));
HashSet<Integer> set2 = new HashSet<Integer>(Arrays.asList(i2));
set1.retainAll(set2);
System.out.println(set1);
}
}

40) What are the different methods available in an ArrayList?

– size() method returns number of elements present in an ArrayList.
– isEmpty() method of ArrayList is used to check whether the given ArrayList is empty or not.
– contains() methods checks the ArrayList contains the given element or not.
– indexOf() method returns index of first occurrence of a specified element.
– lastIndexOf() method returns index of last occurrence of a specified element in an ArrayList.
– toArray() method returns an array containing all elements of the ArrayList.
– get() method returns an element from a specified position of an ArrayList.
– set() method replaces a particular element in an Arraylist with the given element.
– add() method is used to insert an element at a particular position of an ArrayList.
– remove() method is used to remove an element from a particular position of an ArrayList.
– clear() method removes all elements of an ArrayList.
– addAll() method which takes Collection type as an argument to join two ArrayLists.

Share

Bijan Patel

Founder & Creator of QAScript | 12+ years of IT Experience | Full Stack Automation Engineer | Blogger | Trainer

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!