0% found this document useful (0 votes)
3 views

Collection interview QA

The document provides an overview of key differences between various Java collection types, including List, Set, ArrayList, LinkedList, HashMap, and ConcurrentHashMap. It explains concepts such as ordering, duplication, performance, and thread safety, as well as internal workings like collision handling and resizing in HashMap. Additionally, it discusses the use of Comparable and Comparator interfaces for sorting and the significance of fail-fast and fail-safe iterators.

Uploaded by

mail2kumarlalit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Collection interview QA

The document provides an overview of key differences between various Java collection types, including List, Set, ArrayList, LinkedList, HashMap, and ConcurrentHashMap. It explains concepts such as ordering, duplication, performance, and thread safety, as well as internal workings like collision handling and resizing in HashMap. Additionally, it discusses the use of Comparable and Comparator interfaces for sorting and the significance of fail-fast and fail-safe iterators.

Uploaded by

mail2kumarlalit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 26

Collection Interview Q/A

1. What is the difference between List and Set?

- List:
A List is an ordered collection that allows duplicate elements.

It maintains the insertion order, meaning that the elements are stored and retrieved in the same order
they were added.

Examples of List implementations include ArrayList, LinkedList, and Vector.

- Set:
A Set is an unordered collection that does not allow duplicate elements.

It does not maintain any specific order, and elements are stored and retrieved without any particular
sequence.

Examples of Set implementations include HashSet, TreeSet, and LinkedHashSet.

When to use List:

Use List when you need to maintain a collection of elements in a specific order, allow duplicate
elements, or access elements by their index.

When to use Set:

Use Set when you need to store a collection of unique elements without duplicates, don't care about the
order of elements, or quickly check if an element exists in your collection.

2. What is the difference between ArrayList and LinkedList?

Key differences

- Insertion and deletion: LinkedList is generally faster for insertion and deletion operations, especially
when inserting or deleting elements at arbitrary positions, since only the affected nodes need to be
updated. ArrayList may require shifting all elements after the insertion or deletion point.

- Random access: ArrayList provides faster random access to elements, since it can directly access any
element using its index. LinkedList requires traversing the list from the beginning to access an element at
a specific position.

- Cache performance: ArrayList tends to have better cache performance, since its elements are stored
contiguously in memory.

3. What happen when we declare the List field with the final keyword?

Best practices

- Use final for fields that should not be reassigned, but may still need to be modified (e.g., a List that is
initialized once and then modified).

- Consider using Collections.unmodifiableList() or ImmutableList from Guava if you need to create


an immutable List.

4. How can i write own Custom ArrayList where I don't want to allow Duplicates ?
Just by overriding ArrayList's add method and provide own impl. as shown below

5. Why Set does not allow duplicate elements?

Any implementation of Set interface uses put() method of Map to store the element as a key in the Map
and key is always unique in Map.

How Sets prevent duplicates

- Hash code and equals method:


Sets use the hash code and equals method of an object to determine whether it is already present in the
set. If an object with the same hash code and equals method is already present, the set will not add it
again.

- HashSet implementation:
The HashSet implementation, which is a common implementation of the Set interface, uses a hash table
to store its elements. When you try to add an element that is already present, the hash table will simply
ignore it.

5. What is the difference between Comparable and Comparator?

Comparable Interface

Purpose:
The Comparable interface is used to define the natural ordering of objects of a class. A class that
implements Comparable can compare its instances with one another using the compareTo() method.

Where it's used:


It is used when objects of a class need to be sorted based on a natural order, such as sorting integers in
ascending order or strings in lexicographical order.
Comparator Interface

Purpose:
The Comparator interface is used to define a custom ordering of objects. You can use it when you want
to sort objects based on multiple or different attributes.
Where it's used:
It is used when you want to define multiple ways of sorting objects, or when you don't want to modify
the class itself (i.e., when you can't modify the class to implement Comparable).
Use Comparable when:
- The class has a natural ordering (like age, or alphabetical order).
- You only need to define one way to compare objects.

Use Comparator when:


- You need to define multiple comparison strategies (for example, sorting by age or name).
- You don’t want to modify the class itself or you can’t (for example, if you don’t have access to
modify the class).

6. What is the difference between fail fast and fail safe interator?

Example :

trying to add in middle of iteration


then will get ConcurrentModificationException

And to avoid this Exception we can use CopyOnWriteArrayList instead of ArrayList

in case of CopyOnWriteArrayList a clone copy of collection and any update happen to that clone copy
instead of actual collection.
7. what is the need of ConcurrentHashMap and it is different from HashMap?

ConcurrentHashMap is a thread-safe, highly efficient implementation of the Map interface that allows
concurrent access and modification by multiple threads, and specifically designed for scenarios where
multiple threads need to read and write to the map concurrently without causing issues like data
inconsistency or thread contention.

Key Differences in Behavior:

Thread Safety: HashMap is not thread-safe, while ConcurrentHashMap provides a thread-safe


mechanism with a fine-grained lock system.

Locking: HashMap does not have locking and relies on external synchronization. On the other hand,
ConcurrentHashMap uses a segment-based locking mechanism, allowing high concurrency by locking
only a portion of the map, reducing contention.

Null Values: HashMap allows null keys and values, while ConcurrentHashMap does not allow null for
either keys or values. This restriction ensures that null values cannot cause ambiguity in concurrent
environments.

Performance: ConcurrentHashMap provides better performance in multi-threaded applications because


read operations do not block other threads, and its internal structure allows for concurrent reads and
writes.

Example:
Globally declaring a map and on a seperate thread I am adding an element to this map,
and in main thread I am add few for elements to map and iterating the map
will get ConcurrentModificationException in case of HashMap

but with ConcurrentHashMap will allow us to add and iterate the map at same time
8. If we have HashTable which is already synchronized then why we need
ConcurrentHashMap?

Locking Mechanism:

Hashtable:
In Hashtable, the entire map is locked during each read and write operation. This means that when one
thread is accessing or modifying the map, no other thread can access or modify it, even if they are
working on different keys or values.

This is a global lock on the entire map, which results in a significant performance bottleneck under high
concurrency. Only one thread can access the map at a time, even for operations that are independent
(e.g., reading or writing different keys).
ConcurrentHashMap:
ConcurrentHashMap uses a segment-based locking mechanism (in earlier versions, it divided the map
into segments, and each segment could be locked independently). In modern versions of
ConcurrentHashMap, it uses bucket-level locking or lock striping (using finer-grained locks).

This means that multiple threads can concurrently access and modify different parts of the map
simultaneously without blocking each other. For example, one thread could be reading from one bucket,
while another thread is modifying a different bucket.

9. We can Synchronize a HashMap using Collections then why can not we use that instead
using ConcurrenHashMap?

Synchronizing a HashMap using Collections


The Collections.synchronizedMap() method returns a synchronized view of the underlying map. This
means that only one thread can access the map at a time, which can lead to performance issues in multi-
threaded environments.

ConcurrentHashMap
ConcurrentHashMap, on the other hand, is a thread-safe implementation of a map that allows multiple
threads to access and modify the map concurrently.
Key differences
The key differences between synchronizing a HashMap using Collections and using a
ConcurrentHashMap are:

- Locking mechanism: Synchronizing a HashMap using Collections uses a single lock for the entire map,
whereas ConcurrentHashMap uses a segmented locking mechanism, which allows multiple threads to
access different segments of the map concurrently.

- Performance: ConcurrentHashMap is generally faster and more efficient than synchronizing a HashMap
using Collections, especially in multi-threaded environments.
10. How HashMap internally works?
A HashMap uses an array of buckets, where each bucket is essentially a linked list.

When you put a key-value pair in a HashMap, it calculates a hash code of the key using Object's class
hashCode method, then maps this hash code to an index in the array (bucket) using the formula:
index = (n - 1) & hash
Example:

creating a HashMap of Employee and putting e1 object to map then HashCode calculated to 6 so this
entry put into 6th index in map

Collision Handling:
Collisions occur when two keys have the same index. HashMap handles collisions using:

a. Chaining with LinkedList


Initially, collided entries are stored in a linked list at the same bucket index.

b. Treeification (Java 8+)


If a bucket contains more than 8 entries, it is converted from a LinkedList to a Red-Black Tree for
faster lookup (O(log n) instead of O(n)).

e3 object also has same hascode to e1 so it stores in


same 6th index and previous node pointer points to e3 node.

Note: can we have null key in HashMap and if yes then what will be the hashcode for that ?
yes we can store single null as a key and hashcode for that will be 0.

Resizing (Rehashing):
When the number of entries exceeds the load factor (default 0.75), the HashMap doubles its
capacity and rehashes all entries to new buckets. This is an expensive operation.

get() Operation:
HashMap calculates the hash of the key.
Maps it to the bucket index.
Traverses the bucket (LinkedList or Tree) to find the correct key.
Returns the associated value.

What happens if two keys have the same hashCode?


They go to the same bucket. HashMap uses equals() to differentiate between them.

What’s the difference between HashMap and Hashtable?


HashMap is not synchronized; Hashtable is. Also, HashMap allows null keys/values; Hashtable doesn’t.
searching in LinkedList
java 8 enhancement

11. What is LinkedHasMap and It’s internal working?


Node of a LinkedHashMap:

How elements added to LinkedHashMap:


Adding Next Element and Connecting to Previous Node:

Working of Get Method in LinkedHashMap:


Coding example to show the difference between HashMap and LinkedHashMap:
Output:

12. Important HashMap Interview Q/A


1. How does the put method work in HashMap internally?
The put method works on the hashing principle. It calculates the hash code of the key
and then calculates the index based on the hash code. The key-value pair is then stored
at the calculated index.

2. What is the requirement for an object to be used as a key or value in HashMap?


The key object should implement the hashCode() and equals() methods.

3. What will happen if you try to store a value with a key that is already present in
HashMap?
If you store an existing key in HashMap, it will overwrite the old value with the new
value, and the put method will return the old value.

4. Can you store a null key in HashMap?


Yes, HashMap allows one null key.

5. Can you store a null value inside HashMap?


Yes, HashMap allows multiple null values.

6. How does HashMap handle collision in Java?


HashMap handles collision by storing the colliding elements in a linked list or a balanced
binary tree (after JDK 1.8) at the same index.

7. Which data structure does HashMap represent?


HashMap represents a data structure that combines a hash table and a linked list or a
balanced binary tree.

8. Can you store a duplicate key in HashMap?


No, HashMap does not allow duplicate keys.

9. Is HashMap thread-safe in Java?


No, HashMap is not thread-safe.

10. What will happen if you use HashMap in a multi-threaded Java application?
If you use HashMap in a multi-threaded environment, the internal data structure of
HashMap may get corrupted, and the data might be inconsistent. You can either use
ConcurrentHashMap and Collections.synchronizedMap()
11. What are the different ways to iterate over HashMap?
You can iterate over HashMap using keySet(), entrySet(), and forEach() methods.

2. Using keySet()

3. Using forEach method

12. How do you remove a mapping while iterating over HashMap in Java?
You can use the remove() method to remove a key-value pair while iterating over
HashMap.

13. In which order are mappings stored in HashMap?


HashMap does not maintain any order.

14. Can you sort the HashMap in Java?


No, you cannot sort HashMap directly. However, you can convert it to a LinkedHashMap
or use a SortedMap.

15. What is the load factor in HashMap?


The load factor is a measure that determines when to resize the HashMap. When the
number of elements exceeds the load factor (75% or 0.75) threshold, the HashMap is
resized.

16. How does resizing happen in HashMap?


When the HashMap becomes more than 75% full (default load factor), it triggers
resizing, which involves doubling the number of buckets.

17. How many entries can you store in HashMap?


There is no limit on the number of entries you can store in HashMap until you run out of
memory.

18. What is the difference between the capacity and size of HashMap?
Capacity refers to the number of buckets in the HashMap, while size refers to the
number of key-value pairs currently stored.

19. What will happen if two different keys of HashMap return the same hash code?
If two different keys return the same hash code, a collision will occur, and the colliding
elements will be stored in a linked list or a balanced binary tree.

11. How TreeMap internally works?


A TreeMap in Java is a NavigableMap implementation based on a Red-Black Tree, which is a type
of self-balancing binary search tree. Unlike HashMap, which is unordered, TreeMap maintains
the natural ordering of keys (or uses a custom Comparator).

TreeMap is implemented using a Red-Black Tree, which ensures O(log n) time complexity for all major
operations like get(), put(), remove().

You might also like