Govt Exams
offer() returns false if element cannot be added, while add() throws exception. poll() returns null if empty.
Vector is a legacy synchronized collection similar to ArrayList. It is thread-safe but slower. ArrayList is preferred with Collections.synchronizedList() for synchronization.
SortedSet and SortedMap interfaces provide sorted ordering. TreeSet implements SortedSet, TreeMap implements SortedMap.
Map map = new HashMap();
map.put("A", 10);
map.put("B", 20);
map.put("A", 30);
What will be the size of map?
HashMap stores unique keys. Putting same key 'A' again replaces the old value. Size remains 2 with keys A and B.
LinkedList provides O(1) insertion/deletion at ends and O(n) at middle. ArrayList requires O(n) for middle insertions/deletions due to shifting.
Comparable interface provides compareTo() method to define natural ordering for objects. Used by TreeSet and TreeMap for sorting.
ConcurrentHashMap is thread-safe and uses bucket-level locking. HashMap, TreeMap, and LinkedHashMap are not thread-safe.
TreeSet is backed by a TreeMap which uses Red-Black tree. Add operation requires O(log n) time for tree balancing.
Load factor is the ratio of size to capacity. Default load factor in HashMap is 0.75, which provides good balance between time and space complexity.
Using remove() directly in loop causes ConcurrentModificationException. Iterator.remove() is the safe way to remove elements while iterating.