Java Collection Interview Questions For Experienced

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

Java provides two interfaces to sort objects using data members of the class: 

  • Comparable
  • Comparator

Comparable

Comparator

The Comparable interface provides a single sorting sequence.The Comparator interface provides multiple sorting sequences.
The actual class is modified by a comparable interfaceThe actual class is not modified by the Comparator interface.
compareTo() method is used to sort elements.compare() method is used to sort elements.
Comparable is present in the package java.langComparator is present in the package java.util

For more information, refer to the article – Comparable vs Comparator in Java

30. What is the difference between fail-fast and failsafe?

Iterators in Java are used to iterate over the Collection objects. Fail-Fast iterators immediately throw ConcurrentModificationException if there is a structural modification of the collection. Structural modification means adding, or removing any element from a collection while a thread is iterating over that collection. Iterator on ArrayList and HashMap classes are some examples of fail-fast Iterator.

                                           Fail-Fast                                               Fail-Safe
ConcurrentModificationException is thrown while modifying the object during the iteration process.No Exception is thrown
Fail-Fast needs less memory during the process.Fail-Safe iterator requires more memory during the process.                                                                    
A clone Object is not created during the iteration process.A clone Object or a Copy is created during the iteration process.
Fail-Fast does not allow modification during the process of iteration.Fail-Safe allows modification during the process of iteration.
Fail-Fast is fast,Fail-Safe is slightly slower than fail fast.

Examples:

ArrayList, Vector, HashMap, HashSet, etc.

Examples:

ConcurrentHashMap, CopyOnWriteArrayList, etc.

For more information, refer to the article – Fail Fast and Fail Safe Iterators in Java

31. Write a program to iterate the list using the lambda expression.

Iteration can be done using a lambda expression.

Syntax:

list_name.forEach(variable->{//block of code})

Java
// Java Program to iterate over a List
// using forEach()

// Importing all classes of
// java.util method
import java.util.*;

// Class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an ArrayList
        List<String> l = new ArrayList<String>();

        // Adding elements to the List
        // Custom inputs
        l.add("Geeks");
        l.add("for");
        l.add("Geeks");

        // Lambda expression printing all elements in a List
        l.forEach((temp) -> { System.out.println(temp); });
    }
}

Output
Geeks
for
Geeks



For more information, refer to the article – Iterate through List in Java

32. What is IdentityHashMap?

The IdentityHashMap implements the Map interface using Hashtable, comparing keys (and values) using reference equality instead of object equality. This class implements the Map interface, but it intentionally breaks Map’s general contract, which demands that objects are compared using the equals() method. This class is used when the user allows objects to be compared using references. It belongs to java.util package.

For more information, refer to the article – IdentityHashMap class in Java

33. Write a program in Java to display the contents of a HashTable using enumeration.

The hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. Below is the program to display the contents of a HashTable using enumeration:

Java
// Java Program to Demonstrate Getting Values
// as an Enumeration of Hashtable class

import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;

// Main class
// EnumerationOnKeys
public class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty hashtable
        Hashtable<Integer, String> hash
            = new Hashtable<Integer, String>();

        // Inserting key-value pairs into hash table
        // using put() method
        hash.put(1, "Geeks");
        hash.put(2, "for");
        hash.put(3, "Geeks");

        // Now creating an Enumeration object
        //  to read elements
        Enumeration e = hash.elements();

        // Condition holds true till there is
        // single key remaining

        // Printing elements of hashtable
        // using enumeration
        while (e.hasMoreElements()) {

            // Printing the current element
            System.out.println(e.nextElement());
        }
    }
}

Output
Geeks
for
Geeks



34. Write a program in java to get the collection view of the values present in a HashMap.

Java’s HashMap class has the java.util.HashMap.values() method for creating collections out of HashMap values. It basically returns a Collection view of HashMap values.

Java
// Java code to illustrate the values() method
import java.util.*;

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

        // Creating an empty HashMap
        HashMap<Integer, String> hash_map
            = new HashMap<Integer, String>();

        // Mapping string values to int keys
        hash_map.put(0, "Welcome");
        hash_map.put(1, "to");
        hash_map.put(2, "Geeks");
        hash_map.put(3, "4");
        hash_map.put(4, "Geeks");

        // Displaying the HashMap
        System.out.println("Initial Mappings are: "
                           + hash_map);

        // Using values() to get the set view of values
        System.out.println("The collection is: "
                           + hash_map.values());
    }
}

Output
Initial Mappings are: {0=Welcome, 1=to, 2=Geeks, 3=4, 4=Geeks}
The collection is: [Welcome, to, Geeks, 4, Geeks]



For more information, refer to the article – HashMap values() Method in Java

35. Write a program to join two ArrayList into one single ArrayList.

Given two ArrayLists in Java, our task is to join these ArrayLists.

Java
// Java program to demonstrate
// How to join ArrayList

import java.util.*;

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

        ArrayList<String> list_1 = new ArrayList<String>();

        list_1.add("Geeks");
        list_1.add("For");
        list_1.add("ForGeeks");

        // Print the ArrayList 1
        System.out.println("ArrayList 1: " + list_1);

        ArrayList<String> list_2 = new ArrayList<String>();

        list_2.add("w3wiki");
        list_2.add("A computer portal");

        // Displaying the ArrayList 2
        System.out.println("ArrayList 2: " + list_2);

        // using Collection.addAll() method to join two
        // arraylist
        list_1.addAll(list_2);

        // Print the joined ArrayList
        System.out.println("Joined ArrayLists: " + list_1);
    }
}

Output
ArrayList 1: [Geeks, For, ForGeeks]
ArrayList 2: [w3wiki, A computer portal]
Joined ArrayLists: [Geeks, For, ForGeeks, w3wiki, A computer portal]



For more information, refer to the article – Join two ArrayLists in Java

36. How can you synchronize an ArrayList in Java?

Using the Collections.synchronizedList() method, we can synchronize our collections in Java. SynchronizedList() returns a synchronized (thread-safe) list backed by a selection.

Java
// Java program to show synchronization of ArrayList
import java.io.*;
import java.util.*;

class GFG {
    public static void main(String[] args)
    {
        // Non Synchronized ArrayList
        List<String> list = new ArrayList<String>();

        list.add("Eat");
        list.add("Coffee");
        list.add("Code");
        list.add("Sleep");
        list.add("Repeat");

        // Synchronizing ArrayList in Java
        list = Collections.synchronizedList(list);

        // we must use synchronize block to avoid
        // non-deterministic behavior
        synchronized (list)
        {
            Iterator<String> it = list.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
        }
    }
}

Output
Eat
Coffee
Code
Sleep
Repeat



37. What is a Properties Class in Java? 

The properties class is a subclass of Hashtable. The properties class stores a list of values whose key is a string and whose value is also a string. Properties can define other properties class lists, but the default is properties.

Features of Properties class:

  • Property is a subclass of Hashtable.
  • The Properties file is used to store and retrieve string data type for a list of values where the key is a string and the value is also a string.
  • If the original properties list does not contain a certain key property, the default properties list will be searched instead.
  • Objects can be shared by multiple threads without external synchronization.
  • The properties class can be used to retrieve the properties of the system.

For more information, refer to the article – Properties Class in Java

38. What will happen if you use HashMap in a multithreaded Java application?

In a multi-threaded environment, if multiple threads alter the map structurally, such as adding, removing, or modifying mappings, the internal data structure of HashMap may become corrupted and there may be some missing links, incorrect entries, and the map itself may become completely useless. Thus, you should not use HashMap in a concurrent application; instead, use ConcurrentHashMap or Hashtable which is thread-safe. The ConcurrentHashMap includes all the Hashtable’s methods as well as full concurrency of retrievals and updates.

How did ThreadSafeConcurrentHashMap become thread-safe? 

  • java.util.Concurrent.ConcurrentHashMap class provides thread safety by dividing the map into segments, which allows the lock to be taken only once per segment, i.e, once for each thread.
  • The read operation in ConcurrentHashMap does not require a lock. 

For more information, refer to the article – How Does ConcurrentHashMap Achieve Thread-Safety in Java?

39. What will happen if two different keys of HashMap return the same hashcode()?

When two different keys of HashMap return the same hash code, they will end up in the same bucket; therefore, collisions will occur. n case of collision, i.e. index of two or more nodes is the same, nodes are joined by a link list i.e. the second node is referenced by the first node and the third by the second, and so on.

For more information, refer to the article – Internal Working of HashMap in Java

40. What is WeakHashMap?

WeakHashMap implements the Map interface. Unlike HashMap, WeakHashMap allows garbage collection even if the object specified as the key doesn’t contain any references despite being associated with WeakHashMap. In other words, Garbage Collector is better than WeakHashMap.

For more information, refer to the article – Hashmap vs WeakHashMap in Java

41. What is UnsupportedOperationException?

In the context of APIs or list implementations, the UnsupportedOperationException is a common exception. The exception is thrown when the requested operation cannot be performed. This class is a member of the Java Collections Framework.

Syntax:

public class UnsupportedOperationException
extends RuntimeException

For more information, refer to the article – UnsupportedOperationException

42. How to make a Collection Read-Only in Java?

Creating a Read-Only Collection involves restricting the object to only fetching the data and not adding or removing data. Java has different methods for different Collection types like unmodifiableCollection(), unmodifiableMap(), ununmodifiableSet(), etc. java.util.The collections class defines all methods. The unmodifiableCollection() method creates a Read-Only collection. It requires a reference to the Collection class. If we have an object of Set Interface, we can use ununmodifiableSet() to make Read-Only.

For more information, refer to the article – How to Make a Collection Read-Only in Java?

43. Difference between PriorityQueue and TreeSet in Java? 

                   PriorityQueue

                                TreeSet

PriorityQueue comes in JDK 1.5.TreeSet comes in JDK 1.4.
The data structure used by PriorityQueue is QueueThe data structure used by TreeSet is Set.
Duplicate elements are allowed.Duplicate elements are not allowed.
Except for the root element, the rest of the elements do not follow any particular order in PriorityQueue.In TreeSet all the elements remain in the sorted order.
Using PriorityQueue, we can retrieve the largest or smallest element in O(1) time.TreeSet doesn’t provide a way to retrieve the largest or smallest element in O(1) time, but since they are in sorted order it gets the first or last element in O(1) time.

For more information, refer to the article – Difference Between PriorityQueue and TreeSet

44. What is the diamond operator in Java?

Diamond operators are used for simplifying the use of generics when creating objects while avoiding unchecked warnings in a program. When the Diamond operator was introduced in Java 7, we can create the object without mentioning the generic type on the right side of the expression as shown below.

Syntax:

List<String> list = new ArrayList<>();

For more information, refer to the article – Diamond operator

45. How TreeMap works in Java?

TreeMap stores the key-value pairs, but TreeMap sorts the keys ascending rather than descending like HashMap. Depending on which constructor is used, TreeMap will be sorted either based on its keys, or by a Comparator. In TreeMap, the elements are sorted based on a Red-Black tree. A red-black tree is a self-balancing binary search tree where each node has an extra bit, and that bit is often interpreted as the color (red or black). These colors are used to ensure that the tree remains balanced during insertions and deletions. 

Structure of a Node in Java

For more information, refer to the article – Internal Working of TreeMap in Java

46. List down ways to iterate over Map in java?

The HashMap class provides Java’s Map interface by storing data in (Key, Value) pairs and accessing them by an index of another type. To use this class it is necessary to import java.util.HashMap package or its superclass.

There are numerous ways to iterate over HashMap of which 5 are listed below:

  1. Iterate through a HashMap EntrySet using Iterators.
  2. Iterate through HashMap KeySet using Iterator.
  3. Iterate HashMap using for-each loop.
  4. Iterating through a HashMap using Lambda Expressions.
  5. Loop through a HashMap using Stream API.

For more information, refer to the article – How to Iterate HashMap in Java

47. What is CopyOnWriteArrayList in Java?

CopyOnWriteArrayList in Java

JDK 1.5 introduced an enhanced version of ArrayList called CopyOnWriteArrayList, where all modifications (add, set, remove, etc) are implemented by a new copy. It can be found in java.util.concurrent. It is a data structure created to be used in a concurrent environment. In a Thread-based environment, the CopyOnWriteArrayList is intended for frequent reading and infrequent updating. CopyOnWriteArrayList is a thread-safe version of  ArrayList.

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

48.  What is EnumMap in Java?

EnumMap is an implementation of the Map interface specific to enumeration types. EnumMap class is a member of the Java Collections Framework & is not synchronized. It extends AbstractMap and implements the Map interface in java. EnumMap belongs to java.util package.

Syntax: 

public class EnumMap<K extends Enum<K>,​V> extends AbstractMap<K,​V> implements Serializable, Cloneable

// K must extend Enum, which enforces the requirement that the keys must be of the specified enum type. 

Parameters:

  • Key object type
  • Value object type

EnumMap in Java

For more information, refer to the article – EnumMap class in Java

49. How does Hashmap internally Works?

HashMap works on the principle of Hashing. HashMap contains an array of Node and Node can represent a class having the following objects:

  • int hash
  • K key
  • V value
  • Node next

The internal workings of HashMap:

  • Hashing
  • Buckets
  • Index Calculation in Hashmap

For more information, refer to the article – Internal Working of HashMap in Java

50. Why iterator in hashmap is considered fail-fast?

fail-fast iterators immediately throw concurrent modification exceptions if any thread from outside attempts to modify the collection on which they are iterating. The fail-fast feature ensures that the iterator fails immediately if it detects that any modification of the collection will lead to anomalous behavior in the future.

Fail fast feature ensures that if iterator feels that modification of collection would result in anomalous behaviour at any point of time in future, it fails immediately.

Example:

Java
// Java code to demonstrate remove
// case in Fail-fast iterators

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;

public class GFG {
    public static void main(String[] args)
    {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        arr.add(5);

        Iterator<Integer> it = arr.iterator();
        while (it.hasNext()) {
            if (it.next() == 2) {
                // will not throw Exception
                it.remove();
            }
        }

        System.out.println(arr);

        it = arr.iterator();
        while (it.hasNext()) {
            if (it.next() == 3) {
                // will throw Exception on
                // next call of next() method
                arr.remove(3);
            }
        }
    }
}

Output:

[1, 3, 4, 5]
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at FailFastExample.main(FailFastExample.java:28)

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