Answer: The Java Collections Framework is a set of classes and interfaces for storing and manipulating groups of objects. Its hierarchy is structured as follows:
-
Interfaces:
CollectionListArrayList,LinkedList,Vector,Stack
SetHashSet,LinkedHashSet,TreeSet
QueuePriorityQueue,Deque
MapHashMap,LinkedHashMap,TreeMap,Hashtable
-
Root Interfaces:
Iterable: Parent ofCollectionMap: Separate interface for key-value pairs
Key Points:
Listis for ordered collections allowing duplicates.Setensures uniqueness of elements.Mapis for key-value pairs.
Answer:
| Feature | List |
Set |
Map |
|---|---|---|---|
| Order | Maintains insertion order | No guaranteed order (except LinkedHashSet) |
Maintains key-value mapping order (e.g., TreeMap sorts keys) |
| Duplicates | Allows duplicates | Does not allow duplicates | Keys are unique; values can be duplicated |
| Examples | ArrayList, LinkedList |
HashSet, TreeSet |
HashMap, TreeMap |
Example:
List<Integer> list = new ArrayList<>();
list.add(1); list.add(1); // Duplicates allowed
Set<Integer> set = new HashSet<>();
set.add(1); set.add(1); // Duplicate ignored
Map<Integer, String> map = new HashMap<>();
map.put(1, "One"); map.put(1, "Uno"); // Key overwrittenAnswer:
-
HashMap:- Does not maintain any order of its elements.
- Faster than
LinkedHashMapas it does not maintain ordering.
-
LinkedHashMap:- Maintains insertion order of elements.
- Slightly slower than
HashMapdue to ordering overhead.
Example:
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "One");
hashMap.put(2, "Two");
System.out.println(hashMap); // Random order
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put(1, "One");
linkedHashMap.put(2, "Two");
System.out.println(linkedHashMap); // Insertion orderAnswer:
-
Queue:- Follows the FIFO (First-In-First-Out) principle.
- Examples:
PriorityQueue,LinkedList.
-
Deque:- Stands for Double-Ended Queue.
- Allows insertion and deletion from both ends.
- Examples:
ArrayDeque,LinkedList.
Example:
Queue<Integer> queue = new LinkedList<>();
queue.add(1); queue.add(2);
System.out.println(queue.poll()); // Removes 1 (FIFO)
Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(1); deque.addLast(2);
System.out.println(deque.pollLast()); // Removes 2Answer:
-
NavigableSet:- A
SortedSetwith additional methods for navigation likelower(),higher(),ceiling(), andfloor(). - Example:
TreeSet.
- A
-
NavigableMap:- A
SortedMapwith additional navigation methods. - Example:
TreeMap.
- A
Example:
NavigableSet<Integer> navigableSet = new TreeSet<>();
navigableSet.add(10);
navigableSet.add(20);
System.out.println(navigableSet.lower(15)); // Output: 10
NavigableMap<Integer, String> navigableMap = new TreeMap<>();
navigableMap.put(1, "One");
navigableMap.put(2, "Two");
System.out.println(navigableMap.floorEntry(1).getValue()); // Output: OneAnswer:
- A
TreeMapmaintains its order using the natural ordering of its keys or a customComparatorprovided at the time of creation. - It implements a Red-Black Tree internally, ensuring that the elements are always sorted.
Example:
Map<Integer, String> treeMap = new TreeMap<>();
treeMap.put(2, "Two");
treeMap.put(1, "One");
System.out.println(treeMap); // Output: {1=One, 2=Two}Answer:
-
Comparable:- Used to define natural ordering.
- Implemented using the
compareTo()method. - Example:
String,Integer.
-
Comparator:- Used for custom ordering.
- Implemented using the
compare()method.
Example:
class Student implements Comparable<Student> {
int rollNo;
@Override
public int compareTo(Student o) {
return this.rollNo - o.rollNo;
}
}
Comparator<Student> byName = Comparator.comparing(student -> student.name);Answer:
- A
HashSetis backed by aHashMap. - Each element in the
HashSetis stored as a key in theHashMapwith a dummy value. - The hashing mechanism ensures constant-time performance for basic operations like add, remove, and contains.
Example:
Set<String> set = new HashSet<>();
set.add("One");Internally:
HashMap<String, Object> map = new HashMap<>();
map.put("One", PRESENT);Answer:
- Fail-fast iterators throw a
ConcurrentModificationExceptionif the collection is structurally modified after the creation of the iterator. - This mechanism prevents unpredictable behavior during iteration.
Example:
List<Integer> list = new ArrayList<>();
list.add(1);
Iterator<Integer> iterator = list.iterator();
list.add(2); // Structural modification
iterator.next(); // Throws ConcurrentModificationExceptionAnswer:
- Using synchronized wrappers: Use
Collections.synchronizedList()or similar methods to synchronize a collection. - Using concurrent collections: Use classes like
ConcurrentHashMap,CopyOnWriteArrayList.
Example:
List<Integer> synchronizedList = Collections.synchronizedList(new ArrayList<>());
Map<Integer, String> concurrentMap = new ConcurrentHashMap<>();