This first set of Collections questions builds the map of the framework: why collections exist when we already have arrays, the core interfaces (Collection, List, Set, SortedSet, NavigableSet, Queue, Map, SortedMap, NavigableMap) and the three list classes you must know, ArrayList, LinkedList and Vector. It ends with thread-safe lists and arrays versus ArrayList.
A good habit: as you read, sketch the hierarchy on paper (Collection at the top, Map on its own) and place each interface on it. In the interview, say what the interface guarantees (order, duplicates, sorting) before naming classes. Answer each question aloud first, then check.
Q1. How do arrays differ from collections?
Both hold groups of values, but they make different trade-offs.
| Point | Array | Collection |
|---|---|---|
| Size | Fixed when created | Grows and shrinks as needed |
| Primitives | Can hold int, double etc. directly | Objects only; primitives are boxed (Integer) |
| Memory and speed | Compact and fast, especially for primitives | Some overhead for objects and boxing |
| Ready-made operations | Few (helpers in Arrays) | Many: add, remove, contains, sort, stream |
| Type safety | Element type fixed, checked at runtime | Generics, checked at compile time |
Old notes say collections can hold "heterogeneous" objects. A raw collection can, but in modern code you always use generics like List<String>, so both are effectively typed. Use arrays for fixed-size, performance-sensitive data (like a grid of ints) and collections almost everywhere else.
Q2. What are the drawbacks of plain object arrays?
Their size is fixed, so if you do not know how many items will come, you either waste space or have to create a bigger array and copy everything yourself. They also have no built-in behaviour: searching, inserting in the middle, removing or avoiding duplicates all mean writing loops by hand.
Arrays are also covariant, which causes a runtime trap: a String[] can be assigned to an Object[] variable, and storing an Integer into it compiles but throws ArrayStoreException. Generic collections catch that mistake at compile time.
Q3. What is the Collections Framework?
It is the standard architecture in java.util for storing and processing groups of objects, added in Java 1.2. It has three parts: interfaces that define the abstract types (List, Set, Queue, Map and others), implementations that are the concrete data structures (ArrayList, HashSet, HashMap and others), and algorithms such as sorting and searching, mostly in the Collections utility class.
Because all implementations follow the same interfaces, you learn one API and can switch data structures by changing one line.
Q4. Is "Collection API" the same thing as the Collections Framework?
In interviews the two terms are used for the same thing, so do not argue about the wording. If you want to be precise, the framework is the whole design (interfaces, implementations, algorithms), and the API is the public set of types and methods you call, such as add, remove, contains, iterator, stream and forEach.
A strong answer then names the main packages: java.util for the general purpose classes and java.util.concurrent for thread-safe ones like ConcurrentHashMap and CopyOnWriteArrayList.
Q5. What is the Collection interface?
java.util.Collection is the root interface for groups of individual elements. List, Set and Queue all extend it (Map does not). It declares the methods every such group supports: add, remove, contains, size, isEmpty, clear, iterator, toArray, and since Java 8 stream() and removeIf().
The JDK does not provide a class that implements Collection directly. You always pick a more specific type. Collection itself extends Iterable, which is why any collection works in a for-each loop.
Q6. What is the difference between Collection and Collections?
Collection (singular) is an interface, the root type for lists, sets and queues. Collections (plural) is a utility class full of static helper methods that work on collections: sort, reverse, shuffle, max, min, frequency, unmodifiableList, synchronizedList and emptyList, among others. The same naming pattern exists for Array/Arrays and Object/Objects.
Q7. What is the List interface?
A List is an ordered collection: elements keep their insertion order and each has an index starting at 0. Duplicates are allowed, and most implementations allow null. On top of Collection's methods it adds index-based ones like get(i), set(i, e), add(i, e), remove(i) and indexOf(e). Implementations: ArrayList, LinkedList, Vector, CopyOnWriteArrayList.
Q8. What is the Set interface?
A Set holds no duplicates. Whether two elements are duplicates is decided by equals() (and hashCode() for hash-based sets), so if you put your own objects in a HashSet, override both. Set adds no new methods to Collection; it just changes the rules, for example add returns false if the element was already there.
Order depends on the implementation, which old notes often get wrong. HashSet gives no guaranteed order, LinkedHashSet keeps insertion order, and TreeSet keeps elements sorted.
Q9. What is the SortedSet interface?
SortedSet extends Set and keeps its elements in sorted order, either their natural order (they implement Comparable) or the order given by a Comparator passed to the constructor. Like any set it rejects duplicates, and here "duplicate" means the comparison returns 0. It adds methods like first(), last(), headSet(to), tailSet(from) and subSet(from, to). TreeSet is the main implementation.
Q10. What does NavigableSet add on top of SortedSet?
NavigableSet (Java 6) extends SortedSet with "closest match" methods: floor(e) (largest element at most e), ceiling(e) (smallest at least e), lower(e) and higher(e) (strictly less or greater), pollFirst() and pollLast(), and descendingSet(). It still allows no duplicates, and elements stay sorted, not in insertion order. TreeSet and ConcurrentSkipListSet implement it.
import java.util.*;
public class NavigableSetDemo {
public static void main(String[] args) {
NavigableSet<Integer> scores = new TreeSet<>(List.of(40, 10, 30, 20));
System.out.println(scores);
System.out.println(scores.floor(25) + " " + scores.ceiling(25));
System.out.println(scores.headSet(30));
System.out.println(scores.descendingSet());
}
}
[10, 20, 30, 40]
20 30
[10, 20]
[40, 30, 20, 10]
Q11. What is the Queue interface?
Queue (Java 5) represents elements waiting to be processed, usually first in, first out. Each operation comes in two forms: one throws an exception on failure (add, remove, element) and one returns a special value (offer returns false, poll and peek return null). In practice you use the second set.
Common implementations are ArrayDeque (fast FIFO, also works as a stack), LinkedList, PriorityQueue (always gives the smallest element first, by natural order or a Comparator) and the BlockingQueue classes used in producer-consumer code.
Q12. What is the Map interface, and how is it related to Collection?
A Map stores key and value pairs. Keys are unique; values can repeat. Putting a value under an existing key replaces the old value. Map has been part of the framework since Java 1.2 but it does not extend Collection, because its basic unit is a pair, not a single element. You can still get collection views through keySet(), values() and entrySet().
Keys and values must be objects, so primitives are boxed. HashMap allows one null key and null values, TreeMap with natural ordering does not allow a null key, and ConcurrentHashMap allows no nulls at all.
Q13. What is SortedMap?
SortedMap extends Map and keeps its entries sorted by key, using natural ordering or a Comparator. It has been around since Java 1.2 and adds firstKey(), lastKey(), headMap(toKey), tailMap(fromKey) and subMap(from, to). TreeMap is the usual implementation. Use it when you need keys in order, for example to print a leaderboard or a sorted report.
Q14. What is NavigableMap?
NavigableMap (Java 6) extends SortedMap with nearest-key lookups: floorKey/floorEntry, ceilingKey/ceilingEntry, lowerKey, higherKey, firstEntry, pollFirstEntry and descendingMap(). TreeMap and ConcurrentSkipListMap implement it. A neat use is turning ranges into labels, like marks into grades:
import java.util.*;
public class GradeDemo {
public static void main(String[] args) {
NavigableMap<Integer, String> grades = new TreeMap<>();
grades.put(90, "A");
grades.put(75, "B");
grades.put(60, "C");
grades.put(0, "F");
for (int marks : new int[] {95, 82, 60, 41}) {
System.out.println(marks + " -> " + grades.floorEntry(marks).getValue());
}
}
}
95 -> A
82 -> B
60 -> C
41 -> F
Since Java 21, SortedMap also extends the new SequencedMap interface, and SortedSet extends SequencedSet, which give you reversed() and first/last methods on every ordered collection.
Q15. What are the key properties of ArrayList?
ArrayList (Java 1.2) is the resizable-array implementation of List, and the default list you should reach for.
- Backed by an
Object[]. The default capacity is 10, allocated when the first element is added, and it grows by about 50 percent when full. - Keeps insertion order, allows duplicates and nulls.
get(i)is O(1). Adding at the end is O(1) on average. Inserting or removing in the middle is O(n) because elements must shift.- Implements
RandomAccess,CloneableandSerializable. - Not synchronized. Share it between threads only with proper locking or a thread-safe alternative.
Q16. What is the RandomAccess interface?
java.util.RandomAccess is a marker interface with no methods. A List implements it to say "getting an element by index is fast, roughly constant time". Generic algorithms check list instanceof RandomAccess and choose an index-based loop for such lists and an iterator for others, like a linked list where get(i) is slow. ArrayList, Vector and CopyOnWriteArrayList implement it; LinkedList does not.
Q17. What are the key properties of LinkedList?
LinkedList (Java 1.2) is a doubly linked list. It implements both List and Deque, so it also works as a queue or a stack. It keeps insertion order and allows duplicates and nulls. Adding or removing at either end is O(1), but get(i) is O(n) because it has to walk the nodes, and it does not implement RandomAccess.
Textbooks say it is best for frequent inserts in the middle. That is only true if you are already at that spot with an iterator; finding the position is still O(n). In real benchmarks ArrayList or ArrayDeque usually wins because arrays are cache friendly, which is a good point to raise in an interview.
Q18. What is Vector, and is it still used?
Vector is a legacy class from Java 1.0, later retrofitted to implement List. It is a growable array like ArrayList (it doubles in size by default rather than growing by half), keeps order, allows duplicates and nulls, and implements RandomAccess. The main difference is that every method is synchronized, so it is thread safe for single calls but slower, and still unsafe for compound actions like "if absent then add" without extra locking.
New code uses ArrayList, plus CopyOnWriteArrayList or a synchronized wrapper when threads share the list. You will mostly meet Vector in old code and in interview questions.
Q19. How do you get a thread-safe version of an ArrayList?
Wrap it with Collections.synchronizedList(list). Every method call on the wrapper locks the wrapper object. There are matching methods synchronizedSet, synchronizedMap, synchronizedSortedMap and others, and they return Set and Map respectively. One rule people forget: when you iterate, you must lock the wrapper yourself, because iteration is many calls, not one.
import java.util.*;
public class SyncListDemo {
public static void main(String[] args) {
List<String> names = Collections.synchronizedList(new ArrayList<>());
names.add("Riya");
names.add("Arjun");
synchronized (names) {
for (String n : names) {
System.out.println(n);
}
}
}
}
Riya
Arjun
For lists that are read far more than written, CopyOnWriteArrayList is often better: reads need no locking and iteration never throws ConcurrentModificationException. For maps, use ConcurrentHashMap instead of a synchronized map.
Q20. How is an array different from an ArrayList?
An ArrayList is built on top of an array, so the differences are about what the wrapper adds.
- Size: an array's length is fixed; an ArrayList resizes itself.
- Primitives:
int[]stores ints directly;ArrayList<Integer>stores boxed objects, which uses more memory. - Length:
arr.lengthis a field;list.size()is a method. - Syntax: arrays use
arr[i]; lists useget(i)andset(i, x). - Features: ArrayList has add, remove, contains, sort and streams built in, and works with generics.
- Dimensions: arrays can be multi-dimensional directly; with lists you nest them.
Convert with Arrays.asList(arr) (fixed size, backed by the array), List.of(...) (unmodifiable) or new ArrayList<>(Arrays.asList(arr)) when you need a fully modifiable copy.
Quick revision
- Arrays: fixed size, hold primitives. Collections: growable, objects only, rich API.
- Collection is the root interface; Collections is the helper class; Map is not a Collection.
- List: ordered, indexed, duplicates allowed. Set: no duplicates, order depends on the class.
- Sorted and Navigable sets and maps keep items sorted and add floor/ceiling lookups.
- ArrayList is the default list; LinkedList rarely wins in practice; Vector is legacy.
- synchronizedList needs manual locking while iterating; CopyOnWriteArrayList does not.
Frequently asked questions
What is the best way to remember the collection hierarchy?
Draw it from memory once a day for a week: Iterable, Collection, then List, Set and Queue with their main classes, and Map as a separate tree. Add one line under each saying what it guarantees. After a week you will not need notes.
Which collection questions come right after these in interviews?
How HashMap works internally (hashing, buckets, tree bins since Java 8), equals and hashCode contracts, fail-fast versus fail-safe iterators, and Comparable versus Comparator. Be ready to write a custom Comparator with Comparator.comparing.
Should I mention Java 21 sequenced collections?
Yes, briefly. Saying that List, Deque, LinkedHashSet and the sorted types now share getFirst(), getLast() and reversed() shows you follow current Java, and it takes ten seconds.
Next: Part 2 →
See everything in one place: Interview Preparation Hub
Thanks for simple answers
ReplyDelete