0% found this document useful (0 votes)
7 views39 pages

Java Collection Framework Overview

The document provides an overview of the Java Collection Framework, detailing its core interfaces and classes, such as List, Set, and Map. It includes 50 interview questions and answers that cover key concepts, differences between collections, and practical examples of usage. The document serves as a comprehensive guide for understanding and utilizing Java's collection classes effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views39 pages

Java Collection Framework Overview

The document provides an overview of the Java Collection Framework, detailing its core interfaces and classes, such as List, Set, and Map. It includes 50 interview questions and answers that cover key concepts, differences between collections, and practical examples of usage. The document serves as a comprehensive guide for understanding and utilizing Java's collection classes effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link]

com/in/Kunalkr19

JAVA Collection Framework


50 interview questions/answers

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The [Link] package contains all
the classes and interfaces for the Collection framework.
1. What is the Java Collection Framework? Explain its core interfaces.
Explanation: The Java Collection Framework (JCF) provides a set of classes and interfaces to
handle collections of objects. It includes interfaces like Collection, List, Set, Queue, and Map,
and their implementations such as ArrayList, HashSet, LinkedList, and HashMap. These
interfaces and classes provide a standard way to store, access, and manipulate collections.
Example:
java

import [Link].*;

public class CollectionFrameworkExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");

Set<String> set = new HashSet<>();


[Link]("Orange");
[Link]("Apple");

Map<String, Integer> map = new HashMap<>();


[Link]("Key1", 1);
[Link]("Key2", 2);

[Link]("List: " + list);


[Link]("Set: " + set);
[Link]("Map: " + map);
}
}
2. What are the differences between Collection and Collections in Java?
Explanation: Collection is a root interface in the Java Collection Framework that represents a
group of objects. Collections, on the other hand, is a utility class providing static methods to
operate on or return collections (e.g., sorting, searching).
Example:
java

import [Link].*;

public class CollectionVsCollections {


public static void main(String[] args) {
List<String> list = new ArrayList<>([Link]("Banana", "Apple", "Mango"));

// Collections utility class


[Link](list);
[Link]("Sorted List: " + list);

// Collection interface
Collection<String> collection = new ArrayList<>(list);
[Link]("Collection Size: " + [Link]());
}
}
3. How does ArrayList differ from LinkedList? When would you use one over the other?
Explanation: ArrayList is backed by a dynamic array, providing fast random access and slower
insertions/removals in the middle. LinkedList is backed by a doubly linked list, providing
faster insertions/removals but slower access time.
Example:
java

import [Link].*;
public class ArrayListVsLinkedList {
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

List<String> linkedList = new LinkedList<>();


[Link]("Dog");
[Link]("Elephant");
[Link]("Fox");

// Random access
[Link]("ArrayList get(1): " + [Link](1)); // Fast access

// Insertion/removal
[Link](2, "Giraffe");
[Link]("Elephant");
[Link]("LinkedList after modifications: " + linkedList);
}
}
4. Explain the concept of a Set in Java and its implementations.
Explanation: A Set is a collection that does not allow duplicate elements. It is implemented
by HashSet, LinkedHashSet, and TreeSet.
• HashSet: Uses a hash table, does not guarantee any order.
• LinkedHashSet: Maintains insertion order using a linked list.
• TreeSet: Implements NavigableSet and sorts elements according to their natural
ordering or a comparator.
Example:
java
import [Link].*;

public class SetExamples {


public static void main(String[] args) {
Set<String> hashSet = new HashSet<>([Link]("One", "Two", "Three"));
Set<String> linkedHashSet = new LinkedHashSet<>([Link]("A", "B", "C"));
Set<String> treeSet = new TreeSet<>([Link]("X", "Y", "Z"));

[Link]("HashSet: " + hashSet);


[Link]("LinkedHashSet: " + linkedHashSet);
[Link]("TreeSet: " + treeSet);
}
}
5. What is the difference between a List and a Set?
Explanation: A List is an ordered collection that allows duplicate elements and maintains
insertion order. A Set is a collection that does not allow duplicate elements and does not
guarantee any specific order (except LinkedHashSet and TreeSet).
Example:
java

import [Link].*;

public class ListVsSet {


public static void main(String[] args) {
List<String> list = new ArrayList<>([Link]("Apple", "Banana", "Apple"));
Set<String> set = new HashSet<>([Link]("Apple", "Banana", "Apple"));

[Link]("List: " + list); // Allows duplicates


[Link]("Set: " + set); // No duplicates
}
}
6. How does HashSet ensure the uniqueness of elements?
Explanation: HashSet uses a hash table to store elements. Each element’s hash code is
computed and used to place the element in a bucket. When checking for uniqueness,
HashSet checks if the hash code matches and if the element is equal to any existing element
in that bucket.
Example:
java

import [Link].*;

public class HashSetUniqueness {


public static void main(String[] args) {
Set<String> hashSet = new HashSet<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Apple"); // Duplicate, will not be added

[Link]("HashSet: " + hashSet); // Output: [Apple, Banana]


}
}
7. What is a Map in Java? How does it differ from a Collection?
Explanation: A Map is an object that maps keys to values, where each key is unique. It differs
from a Collection as a Collection stores individual elements, while a Map stores key-value
pairs.
Example:
java

import [Link].*;
public class MapVsCollection {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
[Link]("Apple", 1);
[Link]("Banana", 2);

Collection<Integer> values = [Link]();

[Link]("Map: " + map);


[Link]("Values: " + values);
}
}
8. Explain the working of HashMap in Java. How does it store and retrieve data?
Explanation: HashMap uses a hash table for storage. It computes a hash code for each key
and uses it to determine the bucket location. Each bucket holds a linked list of entries to
handle hash collisions. It provides constant-time complexity for basic operations like add,
remove, and contains.
Example:
java

import [Link].*;

public class HashMapWorking {


public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<>();
[Link]("One", 1);
[Link]("Two", 2);

[Link]("HashMap get(\"One\"): " + [Link]("One"));


[Link]("HashMap: " + hashMap);
}
}
9. What are the main differences between HashMap and Hashtable?
Explanation:
• Synchronization: HashMap is not synchronized, while Hashtable is synchronized.
• Null Keys/Values: HashMap allows one null key and multiple null values. Hashtable
does not allow null keys or values.
• Performance: HashMap generally performs better due to the lack of synchronization.
Example:
java

import [Link].*;

public class HashMapVsHashtable {


public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<>();
[Link]("Key1", 1);
[Link](null, 2); // Allowed

Map<String, Integer> hashtable = new Hashtable<>();


[Link]("Key1", 1);
// [Link](null, 2); // Throws NullPointerException

[Link]("HashMap: " + hashMap);


[Link]("Hashtable: " + hashtable);
}
}
10. What is the difference between ArrayList and Vector?
Explanation:
• Synchronization: ArrayList is not synchronized, while Vector is synchronized.
• Growth Policy: ArrayList grows dynamically, while Vector doubles its size when more
space is needed.
• Performance: ArrayList is generally faster than Vector due to lack of synchronization.
Example:
java

import [Link].*;

public class ArrayListVsVector {


public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
[Link]("Apple");

List<String> vector = new Vector<>();


[Link]("Banana");

[Link]("ArrayList: " + arrayList);


[Link]("Vector: " + vector);
}
}
11. How do you convert an array to a List in Java?
Explanation: You can use [Link]() to convert an array to a List. This method returns a
fixed-size list backed by the specified array.
Example:
java

import [Link].*;

public class ArrayToList {


public static void main(String[] args) {
String[] array = {"Apple", "Banana", "Cherry"};
List<String> list = [Link](array);

[Link]("List: " + list);


}
}
12. What are fail-fast and fail-safe iterators?
Explanation:
• Fail-fast: These iterators detect changes to the collection while iterating (e.g.,
ArrayList, HashSet) and throw ConcurrentModificationException.
• Fail-safe: These iterators work on a clone of the collection (e.g.,
CopyOnWriteArrayList) and do not throw exceptions if the collection is modified.
Example:
java

import [Link].*;

public class FailFastVsFailSafe {


public static void main(String[] args) {
List<String> list = new ArrayList<>([Link]("A", "B", "C"));

try {
for (String s : list) {
[Link]("D"); // Modifying the list during iteration
}
} catch (ConcurrentModificationException e) {
[Link]("Fail-fast iterator detected modification.");
}
List<String> copyOnWriteList = new CopyOnWriteArrayList<>([Link]("A", "B",
"C"));
for (String s : copyOnWriteList) {
[Link]("D"); // Safe modification
}
[Link]("CopyOnWriteArrayList: " + copyOnWriteList);
}
}
13. What is the purpose of the Iterator interface in Java?
Explanation: The Iterator interface provides a way to traverse elements of a collection. It
includes methods like hasNext(), next(), and remove() to iterate over and manipulate
elements.
Example:
java

import [Link].*;

public class IteratorExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>([Link]("Apple", "Banana", "Cherry"));
Iterator<String> iterator = [Link]();

while ([Link]()) {
[Link]([Link]());
}
}
}
14. How does ConcurrentModificationException occur in collections?
Explanation: ConcurrentModificationException occurs when a collection is modified while
iterating over it using an iterator, and the modification is detected by the iterator.
Example:
java

import [Link].*;

public class ConcurrentModificationExceptionExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>([Link]("A", "B", "C"));

try {
for (String s : list) {
[Link](s); // Modifying the list during iteration
}
} catch (ConcurrentModificationException e) {
[Link]("ConcurrentModificationException occurred.");
}
}
}
15. What is the difference between Iterator and ListIterator?
Explanation:
• Iterator: Can traverse a collection in one direction (forward) and provides methods
like hasNext(), next(), and remove().
• ListIterator: Extends Iterator and allows bidirectional traversal, modification, and
accessing the current index. Provides methods like hasPrevious(), previous(), and
add().
Example:
java

import [Link].*;

public class ListIteratorExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>([Link]("A", "B", "C"));
ListIterator<String> listIterator = [Link]();

[Link]("Forward iteration:");
while ([Link]()) {
[Link]([Link]());
}

[Link]("Backward iteration:");
while ([Link]()) {
[Link]([Link]());
}
}
}
16. Explain the internal structure of LinkedHashMap. How does it maintain the insertion
order?
Explanation: LinkedHashMap maintains a linked list of entries in addition to the hash table.
This linked list preserves the insertion order of the keys, allowing predictable iteration order.
Example:
java

import [Link].*;

public class LinkedHashMapExample {


public static void main(String[] args) {
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
[Link]("One", 1);
[Link]("Two", 2);
[Link]("Three", 3);
[Link]("LinkedHashMap: " + linkedHashMap);
}
}
17. What is the difference between TreeSet and HashSet?
Explanation:
• TreeSet: Implements NavigableSet and sorts elements according to their natural
ordering or a comparator.
• HashSet: Uses a hash table, does not guarantee any specific order.
Example:
java

import [Link].*;

public class TreeSetVsHashSet {


public static void main(String[] args) {
Set<String> treeSet = new TreeSet<>([Link]("Banana", "Apple", "Cherry"));
Set<String> hashSet = new HashSet<>([Link]("Banana", "Apple", "Cherry"));

[Link]("TreeSet (sorted): " + treeSet);


[Link]("HashSet (unordered): " + hashSet);
}
}
18. Explain how a PriorityQueue works. What are its typical use cases?
Explanation: PriorityQueue is a queue that orders elements according to their natural
ordering or a comparator. It is typically used when elements need to be processed in a
priority order.
Example:
java
import [Link].*;

public class PriorityQueueExample {


public static void main(String[] args) {
Queue<Integer> priorityQueue = new PriorityQueue<>([Link](3, 1, 4, 1, 5, 9));

[Link]("PriorityQueue: ");
while (![Link]()) {
[Link]([Link]()); // Elements are retrieved in priority order
}
}
}
19. What is a Queue in Java, and how does it differ from other collections?
Explanation: A Queue is a collection designed for holding elements prior to processing. It
typically follows a FIFO (first-in-first-out) order. It differs from other collections like List and
Set in its primary purpose and ordering of elements.
Example:
java

import [Link].*;

public class QueueExample {


public static void main(String[] args) {
Queue<String> queue = new LinkedList<>([Link]("A", "B", "C"));

[Link]("Queue (FIFO order):");


while (![Link]()) {
[Link]([Link]());
}
}
}
20. How does a Stack differ from other collection classes?
Explanation: Stack is a subclass of Vector that implements a last-in-first-out (LIFO) stack of
objects. Unlike other collections, Stack allows elements to be pushed and popped according
to LIFO order.
Example:
java

import [Link].*;

public class StackExample {


public static void main(String[] args) {
Stack<String> stack = new Stack<>();
[Link]("A");
[Link]("B");
[Link]("C");

[Link]("Stack (LIFO order):");


while (![Link]()) {
[Link]([Link]());
}
}
}
21. How does ConcurrentHashMap differ from HashMap?
Explanation: ConcurrentHashMap is a thread-safe variant of HashMap. It uses a segmented
locking mechanism for improved concurrency, allowing multiple threads to read and write
concurrently without locking the entire map.
Example:
java

import [Link].*;
public class ConcurrentHashMapExample {
public static void main(String[] args) {
ConcurrentMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<>();
[Link]("A", 1);
[Link]("B", 2);

[Link]("ConcurrentHashMap: " + concurrentHashMap);


}
}
22. What is the purpose of WeakHashMap in Java?
Explanation: WeakHashMap is a map implementation where keys are weakly referenced.
This means that if a key is no longer referenced elsewhere, it may be garbage collected,
allowing the map to automatically clean up unused entries.
Example:
java

import [Link].*;

public class WeakHashMapExample {


public static void main(String[] args) {
Map<String, Integer> weakHashMap = new WeakHashMap<>();
String key = new String("Key");
[Link](key, 1);

[Link]("WeakHashMap before GC: " + weakHashMap);


key = null; // Make key eligible for GC
[Link](); // Suggest GC

[Link]("WeakHashMap after GC: " + weakHashMap);


}
}
23. How does IdentityHashMap differ from HashMap?
Explanation: IdentityHashMap uses reference equality (i.e., ==) instead of object equality
(i.e., equals()) for keys and values, unlike HashMap. This means that two distinct instances
with the same content will be treated as different keys.
Example:
java

import [Link].*;

public class IdentityHashMapExample {


public static void main(String[] args) {
Map<String, Integer> identityHashMap = new IdentityHashMap<>();
String key1 = new String("Key");
String key2 = new String("Key");

[Link](key1, 1);
[Link](key2, 2);

[Link]("IdentityHashMap: " + identityHashMap); // Shows both keys


}
}
24. What is CopyOnWriteArrayList, and how is it different from ArrayList?
Explanation: CopyOnWriteArrayList is a thread-safe variant of ArrayList that creates a new
copy of the underlying array for each modification, ensuring thread safety without requiring
synchronization.
Example:
java

import [Link].*;
import [Link].*;

public class CopyOnWriteArrayListExample {


public static void main(String[] args) {
List<String> copyOnWriteList = new CopyOnWriteArrayList<>([Link]("A", "B",
"C"));
[Link]("D");

[Link]("CopyOnWriteArrayList: " + copyOnWriteList);


}
}
25. Explain the concept of NavigableMap in Java. How does it extend SortedMap?
Explanation: NavigableMap extends SortedMap and provides navigation methods to retrieve
entries based on search criteria. It supports operations like lowerEntry(), floorEntry(),
ceilingEntry(), and higherEntry().
Example:
java

import [Link].*;

public class NavigableMapExample {


public static void main(String[] args) {
NavigableMap<Integer, String> navigableMap = new TreeMap<>();
[Link](1, "One");
[Link](2, "Two");
[Link](3, "Three");

[Link]("Floor Entry for 2: " + [Link](2));


[Link]("Ceiling Entry for 2: " + [Link](2));
}
}
26. What are the differences between Queue, Deque, and BlockingQueue?
Explanation:
• Queue: Represents a collection designed for holding elements prior to processing in
FIFO order.
• Deque: Double-ended queue that allows elements to be added or removed from
both ends.
• BlockingQueue: Extends Queue to support blocking operations when the queue is
full or empty.
Example:
java

import [Link].*;
import [Link].*;

public class QueueTypes {


public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
Deque<String> deque = new ArrayDeque<>();
BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>();

[Link]("QueueElement");
[Link]("DequeElement");
[Link]("BlockingQueueElement");

[Link]("Queue: " + queue);


[Link]("Deque: " + deque);
[Link]("BlockingQueue: " + blockingQueue);
}
}
27. What is the role of Comparator and Comparable in sorting collections?
Explanation:
• Comparable: Interface that defines the natural ordering of objects. Implementing
this interface allows objects to be sorted using [Link]() or [Link]().
• Comparator: Interface that defines an external ordering of objects. It is used to sort
collections in a custom order.
Example:
java

import [Link].*;

public class ComparableComparatorExample {


static class Person implements Comparable<Person> {
String name;
int age;

Person(String name, int age) {


[Link] = name;
[Link] = age;
}

@Override
public int compareTo(Person other) {
return [Link]([Link], [Link]); // Natural order by age
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

static class PersonComparator implements Comparator<Person> {


@Override
public int compare(Person p1, Person p2) {
return [Link]([Link]); // Custom order by name
}
}

public static void main(String[] args) {


List<Person> people = [Link](
new Person("John", 25),
new Person("Jane", 22),
new Person("Alice", 30)
);

[Link](people); // Sorts by age


[Link]("Sorted by age: " + people);

[Link](new PersonComparator()); // Sorts by name


[Link]("Sorted by name: " + people);
}
}
28. How does the hashCode() and equals() methods affect the behavior of collections?
Explanation:
• hashCode(): Determines the bucket in a hash-based collection like HashMap. Objects
with the same hash code may end up in the same bucket.
• equals(): Determines object equality. Two objects with the same hash code but
different equals() results will be stored separately.
Example:
java

import [Link].*;

public class HashCodeEqualsExample {


static class Person {
String name;

Person(String name) {
[Link] = name;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != [Link]()) return false;
Person person = (Person) obj;
return [Link](name, [Link]);
}

@Override
public int hashCode() {
return [Link](name);
}

@Override
public String toString() {
return name;
}
}

public static void main(String[] args) {


Set<Person> set = new HashSet<>();
[Link](new Person("Alice"));
[Link](new Person("Alice")); // Duplicate based on equals() and hashCode()

[Link]("HashSet: " + set);


}
}
29. What is the load factor in a HashMap, and how does it affect performance?
Explanation: The load factor is a measure of how full a hash table is allowed to get before its
capacity is automatically increased. A higher load factor means less space but more
collisions, while a lower load factor means more space but less frequent resizing.
Example:
java

import [Link].*;

public class HashMapLoadFactor {


public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<>(10, 0.75f); // Initial capacity 10, load
factor 0.75

for (int i = 0; i < 15; i++) {


[Link]("Key" + i, i);
}

[Link]("HashMap: " + hashMap);


}
}
30. What are the differences between synchronizedList and CopyOnWriteArrayList?
Explanation:
• synchronizedList: Wraps a list to make it synchronized. All operations are
synchronized, which can affect performance.
• CopyOnWriteArrayList: Provides thread safety by making a new copy of the
underlying array for each modification, allowing read operations to occur
concurrently.
Example:
java

import [Link].*;
import [Link].*;

public class SynchronizedListVsCopyOnWriteArrayList {


public static void main(String[] args) {
List<String> synchronizedList = [Link](new
ArrayList<>([Link]("A", "B", "C")));
List<String> copyOnWriteList = new CopyOnWriteArrayList<>([Link]("A", "B",
"C"));

// Example operations
[Link]("D");
[Link]("D");

[Link]("SynchronizedList: " + synchronizedList);


[Link]("CopyOnWriteArrayList: " + copyOnWriteList);
}
}
31. How can you make a Collection thread-safe in Java?
Explanation: You can make a collection thread-safe using methods from Collections (e.g.,
synchronizedList(), synchronizedMap()) or using concurrent collections like
ConcurrentHashMap or CopyOnWriteArrayList.
Example:
java

import [Link].*;
import [Link].*;

public class ThreadSafeCollections {


public static void main(String[] args) {
List<String> synchronizedList = [Link](new
ArrayList<>([Link]("A", "B", "C")));
ConcurrentMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
[Link]("Key1", 1);
[Link]("Key2", 2);

[Link]("SynchronizedList: " + synchronizedList);


[Link]("ConcurrentMap: " + concurrentMap);
}
}
32. What are Set and its different implementations? How do they differ from List?
Explanation:
• Set: A collection that does not allow duplicate elements. Implementations include
HashSet (unordered), LinkedHashSet (ordered by insertion), and TreeSet (sorted).
• List: A collection that allows duplicate elements and maintains insertion order.
Implementations include ArrayList and LinkedList.
Example:
java

import [Link].*;
public class SetVsList {
public static void main(String[] args) {
Set<String> hashSet = new HashSet<>([Link]("A", "B", "C"));
List<String> arrayList = new ArrayList<>([Link]("A", "B", "C"));

[Link]("HashSet (no duplicates, unordered): " + hashSet);


[Link]("ArrayList (duplicates allowed, ordered): " + arrayList);
}
}
33. What is the role of Collections utility class in Java?
Explanation: The Collections utility class provides static methods for operating on
collections, such as sorting, searching, and shuffling. It also provides methods for creating
synchronized and unmodifiable collections.
Example:
java

import [Link].*;

public class CollectionsUtility {


public static void main(String[] args) {
List<String> list = new ArrayList<>([Link]("Banana", "Apple", "Cherry"));
[Link](list); // Sorting the list
[Link]("Sorted list: " + list);

[Link](list); // Shuffling the list


[Link]("Shuffled list: " + list);

List<String> unmodifiableList = [Link](list);


[Link]("Unmodifiable list: " + unmodifiableList);
}
}
34. What is the difference between [Link]() and [Link]()?
Explanation:
• [Link](): Returns an immutable empty list.
• [Link](): Returns an immutable list containing a single element.
Example:
java

import [Link].*;

public class EmptyAndSingletonList {


public static void main(String[] args) {
List<String> emptyList = [Link]();
List<String> singletonList = [Link]("SingleElement");

[Link]("Empty List: " + emptyList);


[Link]("Singleton List: " + singletonList);
}
}
35. How does TreeMap work, and what is its typical use case?
Explanation: TreeMap implements NavigableMap and is sorted according to the natural
ordering of its keys or a comparator. It provides efficient log(n) time complexity for get, put,
and remove operations. It is typically used when a sorted map is needed.
Example:
java

import [Link].*;

public class TreeMapExample {


public static void main(String[] args) {
Map<String, Integer> treeMap = new TreeMap<>();
[Link]("Banana", 2);
[Link]("Apple", 1);
[Link]("Cherry", 3);

[Link]("TreeMap (sorted by key): " + treeMap);


}
}
36. What is EnumSet and when would you use it?
Explanation: EnumSet is a specialized Set implementation for use with enum types. It is
highly efficient, using bit vectors internally to represent the set of enum values. It is ideal
when working with enum types and you need a set-like structure.
Example:
java

import [Link].*;

public class EnumSetExample {


enum Color {
RED, GREEN, BLUE
}

public static void main(String[] args) {


EnumSet<Color> colorSet = [Link]([Link], [Link]);

[Link]("EnumSet: " + colorSet);


}
}
37. What is the difference between ArrayDeque and LinkedList?
Explanation:
• ArrayDeque: Implements Deque and provides a resizable array implementation,
which is more efficient for stack and queue operations compared to LinkedList.
• LinkedList: Implements both List and Deque and uses a doubly-linked list internally,
which can be less efficient for stack and queue operations compared to ArrayDeque.
Example:
java

import [Link].*;

public class ArrayDequeVsLinkedList {


public static void main(String[] args) {
Deque<String> arrayDeque = new ArrayDeque<>([Link]("A", "B", "C"));
Deque<String> linkedList = new LinkedList<>([Link]("A", "B", "C"));

[Link]("ArrayDeque: " + arrayDeque);


[Link]("LinkedList: " + linkedList);
}
}
38. Explain how TreeSet maintains order.
Explanation: TreeSet maintains order by storing elements in a red-black tree, which is a self-
balancing binary search tree. This ensures that elements are sorted according to their
natural ordering or a provided comparator.
Example:
java

import [Link].*;

public class TreeSetOrder {


public static void main(String[] args) {
Set<String> treeSet = new TreeSet<>([Link]("Banana", "Apple", "Cherry"));
[Link]("TreeSet (sorted): " + treeSet);
}
}
39. How does LinkedHashMap maintain insertion order?
Explanation: LinkedHashMap maintains insertion order by using a linked list to keep track of
the order of entries. The entries are stored in a hash table and linked list, which preserves
the order in which keys were added.
Example:
java

import [Link].*;

public class LinkedHashMapOrder {


public static void main(String[] args) {
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
[Link]("One", 1);
[Link]("Two", 2);
[Link]("Three", 3);

[Link]("LinkedHashMap (insertion order): " + linkedHashMap);


}
}
40. How can you synchronize a Map in Java?
Explanation: You can synchronize a Map using [Link]() which wraps
the map with a synchronized view.
Example:
java

import [Link].*;
public class SynchronizedMapExample {
public static void main(String[] args) {
Map<String, Integer> synchronizedMap = [Link](new
HashMap<>());
[Link]("Key1", 1);
[Link]("Key2", 2);

[Link]("SynchronizedMap: " + synchronizedMap);


}
}
41. What is the purpose of the ConcurrentMap interface?
Explanation: ConcurrentMap is an interface that extends Map and provides additional
methods for concurrency control, such as putIfAbsent(), remove(), and replace() which are
atomic and thread-safe.
Example:
java

import [Link].*;

public class ConcurrentMapExample {


public static void main(String[] args) {
ConcurrentMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
[Link]("Key1", 1);
[Link]("Key1", 2); // No effect, already present

[Link]("ConcurrentMap: " + concurrentMap);


}
}
42. How do you use [Link]() to sort a list of objects?
Explanation: You can use [Link]() to sort a list of objects if the objects implement
Comparable, or you can pass a Comparator to define custom sorting.
Example:
java

import [Link].*;

public class CollectionsSortExample {


static class Person implements Comparable<Person> {
String name;
int age;

Person(String name, int age) {


[Link] = name;
[Link] = age;
}

@Override
public int compareTo(Person other) {
return [Link]([Link], [Link]);
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public static void main(String[] args) {


List<Person> people = [Link](
new Person("John", 25),
new Person("Jane", 22),
new Person("Alice", 30)
);

[Link](people); // Sorts by natural ordering (age)


[Link]("Sorted by age: " + people);
}
}
43. What is the purpose of [Link]()?
Explanation: [Link]() provides a read-only view of the specified
collection. It is used to create immutable collections that prevent modifications.
Example:
java

import [Link].*;

public class UnmodifiableCollectionExample {


public static void main(String[] args) {
List<String> list = [Link]("A", "B", "C");
Collection<String> unmodifiableList = [Link](list);

[Link]("Unmodifiable Collection: " + unmodifiableList);

// The following line will throw UnsupportedOperationException


// [Link]("D");
}
}
44. What are [Link]() and its usage?
Explanation: [Link]() returns a synchronized (thread-safe) list backed
by the specified list. It ensures that all operations on the list are thread-safe.
Example:
java

import [Link].*;

public class SynchronizedListExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>([Link]("A", "B", "C"));
List<String> synchronizedList = [Link](list);

[Link]("D");
[Link]("Synchronized List: " + synchronizedList);
}
}
45. What is the difference between ArrayList and Vector?
Explanation:
• ArrayList: Implements the List interface with a dynamically resizable array. It is not
synchronized.
• Vector: Implements the List interface with a dynamically resizable array but is
synchronized.
Example:
java

import [Link].*;

public class ArrayListVsVector {


public static void main(String[] args) {
List<String> arrayList = new ArrayList<>([Link]("A", "B", "C"));
List<String> vector = new Vector<>([Link]("A", "B", "C"));

[Link]("ArrayList: " + arrayList);


[Link]("Vector: " + vector);
}
}
46. What are [Link]() and its purpose?
Explanation: [Link]() returns an immutable list consisting of n copies of the
specified object. It is useful when you need a fixed-size list where all elements are the same.
Example:
java

import [Link].*;

public class CollectionsNCopiesExample {


public static void main(String[] args) {
List<String> list = [Link](5, "RepeatedElement");

[Link]("List of copies: " + list);


}
}
47. What is PriorityQueue and how is it different from LinkedList?
Explanation: PriorityQueue is a queue where elements are ordered based on their priority. It
does not guarantee a FIFO order like LinkedList but instead provides a way to access the
highest-priority element.
Example:
java

import [Link].*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>([Link](5, 1, 3, 2,
4));

[Link]("PriorityQueue (min-heap): " + [Link]()); // Retrieves


and removes the highest priority element
}
}
48. How does ConcurrentSkipListMap work, and what is its use case?
Explanation: ConcurrentSkipListMap is a concurrent, navigable map implemented using a
skip list. It provides high concurrency and thread-safe operations for maintaining sorted
mappings.
Example:
java

import [Link].*;

public class ConcurrentSkipListMapExample {


public static void main(String[] args) {
ConcurrentSkipListMap<String, Integer> skipListMap = new ConcurrentSkipListMap<>();
[Link]("One", 1);
[Link]("Two", 2);

[Link]("ConcurrentSkipListMap: " + skipListMap);


}
}
49. What are EnumMap and its advantages?
Explanation: EnumMap is a specialized Map implementation for use with enum keys. It is
efficient in terms of performance and space and maintains the natural order of enum
constants.
Example:
java

import [Link].*;

public class EnumMapExample {


enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

public static void main(String[] args) {


EnumMap<Day, String> enumMap = new EnumMap<>([Link]);
[Link]([Link], "Start of the week");
[Link]([Link], "End of the work week");

[Link]("EnumMap: " + enumMap);


}
}
50. How does WeakHashMap handle garbage collection?
Explanation: WeakHashMap uses weak references for its keys, meaning that if a key is no
longer referenced elsewhere, it can be collected by the garbage collector, and its entry in the
WeakHashMap will be removed.
Example:
java

import [Link].*;

public class WeakHashMapExample {


public static void main(String[] args) {
Map<Object, String> weakHashMap = new WeakHashMap<>();
Object key = new Object();
[Link](key, "Value");
[Link]("WeakHashMap before GC: " + weakHashMap);

key = null; // Make key eligible for GC


[Link](); // Suggest GC

[Link]("WeakHashMap after GC: " + weakHashMap);


}
}

[Link]

Common questions

Powered by AI

ConcurrentMap extends the Map interface to provide enhanced concurrency control through atomic operations such as putIfAbsent(), remove(), and replace(). These methods ensure thread-safe manipulations of key-value pairs without the need for explicit synchronization code, making it suitable for concurrent programming where consistent updates are required across multiple threads .

PriorityQueue orders its elements according to their natural order or by a specified comparator at creation time, ensuring elements can be retrieved in priority sequence, typically the highest or lowest priority first. It is ideal for scenarios where tasks or data need prioritization, such as scheduling tasks in an operating system or handling events in real-time processing .

Collections.unmodifiableCollection generates a read-only view of a specific collection, ensuring data immutability. This immutability enhances safety by preventing inadvertent modifications, facilitating concurrent access without locks, and aiding in maintaining consistent states across different parts of an application. It is crucial in design patterns where data integrity is paramount, such as the Observer or Decorator patterns, allowing safe sharing of collection data .

Comparable interface is used for defining natural ordering of objects, which means classes implementing it can be sorted using Collections.sort() directly. It is suitable for cases where there is a single, default way to order objects. Comparator, on the other hand, is used to define custom orderings, allowing flexibility by providing different ordering logic that can be supplied during sorting. This is useful when different sorting criteria are needed, such as sorting by different fields of an object .

Collections.sort() uses the TimSort algorithm, which has a time complexity of O(n log n). For large datasets, this can be computationally expensive, and the performance might degrade further if resources are limited. Mitigating strategies include ensuring that elements implement Comparable efficiently or supplying an optimized Comparator, and choosing data structures like TreeMap or TreeSet that keep elements sorted naturally, reducing the need for repeated sorting operations .

LinkedHashMap maintains insertion order by keeping a linked list of its entries. This linked list ensures that elements are iterated in the order they were inserted. This feature can be desirable in data processing when the order of elements is meaningful, such as when processing a sequence of data entries in the exact order they were received .

hashCode() is used to compute a bucket location in hash-based collections like HashMap, potentially causing different objects with the same hash code to end up in the same bucket. equals() determines object equality; if two objects have the same hash code but are not equal, they will not be regarded as duplicates within the collection. Ensuring that equals() and hashCode() are consistent is crucial for the correct functioning of collections that rely on hash codes .

Using a high load factor in a HashMap allows it to contain more elements before resizing, saving memory space, but it increases the likelihood of hash collisions, leading to longer chains in a bucket and slowing down the retrieval process. Under concurrent modifications, if not handled properly, a high load factor could exacerbate contention and increase latency as threads spend time resolving collisions .

Collections.synchronizedList() wraps a list to make all accesses synchronized, ensuring that only one thread can modify the list at a time. However, this approach can be less efficient than concurrent classes like CopyOnWriteArrayList, which allow multiple reads while writes occur, eliminating the need for synchronization in read scenarios and providing better performance in read-heavy situations .

ConcurrentHashMap should be preferred over Hashtable when high concurrency with better performance is required. It uses a segmented locking mechanism allowing more granularity compared to Hashtable’s single lock for synchronization, hence performing better in scenarios with a high level of concurrent reads and writes .

You might also like