CollectionFramework Java Interview
CollectionFramework Java Interview
import java.util.*;
import java.util.*;
// Collection interface
Collection<String> collection = new ArrayList<>(list);
System.out.println("Collection Size: " + collection.size());
}
}
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 java.util.*;
public class ArrayListVsLinkedList {
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
// Random access
System.out.println("ArrayList get(1): " + arrayList.get(1)); // Fast access
// Insertion/removal
linkedList.add(2, "Giraffe");
linkedList.remove("Elephant");
System.out.println("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 java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
public class MapVsCollection {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
import java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
try {
for (String s : list) {
list.add("D"); // Modifying the list during iteration
}
} catch (ConcurrentModificationException e) {
System.out.println("Fail-fast iterator detected modification.");
}
List<String> copyOnWriteList = new CopyOnWriteArrayList<>(Arrays.asList("A", "B",
"C"));
for (String s : copyOnWriteList) {
copyOnWriteList.add("D"); // Safe modification
}
System.out.println("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 java.util.*;
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
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 java.util.*;
try {
for (String s : list) {
list.remove(s); // Modifying the list during iteration
}
} catch (ConcurrentModificationException e) {
System.out.println("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 java.util.*;
System.out.println("Forward iteration:");
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
System.out.println("Backward iteration:");
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}
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 java.util.*;
import java.util.*;
System.out.println("PriorityQueue: ");
while (!priorityQueue.isEmpty()) {
System.out.println(priorityQueue.poll()); // 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 java.util.*;
import java.util.*;
import java.util.concurrent.*;
public class ConcurrentHashMapExample {
public static void main(String[] args) {
ConcurrentMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.put("A", 1);
concurrentHashMap.put("B", 2);
import java.util.*;
import java.util.*;
identityHashMap.put(key1, 1);
identityHashMap.put(key2, 2);
import java.util.*;
import java.util.concurrent.*;
import java.util.*;
import java.util.*;
import java.util.concurrent.*;
queue.offer("QueueElement");
deque.offerFirst("DequeElement");
blockingQueue.offer("BlockingQueueElement");
import java.util.*;
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age); // Natural order by age
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
import java.util.*;
Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public String toString() {
return name;
}
}
import java.util.*;
import java.util.*;
import java.util.concurrent.*;
// Example operations
synchronizedList.add("D");
copyOnWriteList.add("D");
import java.util.*;
import java.util.concurrent.*;
import java.util.*;
public class SetVsList {
public static void main(String[] args) {
Set<String> hashSet = new HashSet<>(Arrays.asList("A", "B", "C"));
List<String> arrayList = new ArrayList<>(Arrays.asList("A", "B", "C"));
import java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
public class SynchronizedMapExample {
public static void main(String[] args) {
Map<String, Integer> synchronizedMap = Collections.synchronizedMap(new
HashMap<>());
synchronizedMap.put("Key1", 1);
synchronizedMap.put("Key2", 2);
import java.util.concurrent.*;
import java.util.*;
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age);
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
import java.util.*;
import java.util.*;
synchronizedList.add("D");
System.out.println("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 java.util.*;
import java.util.*;
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Arrays.asList(5, 1, 3, 2,
4));
import java.util.concurrent.*;
import java.util.*;
import java.util.*;