Chapter 5: Collections
Multiple Choice · Collections Framework
Question 1: The Collection Family
Which of the following interfaces does not extend the Collection interface?
C: Map holds key-value pairs; it is part of the Collections Framework but does not derive from Collection and is not Iterable. So it cannot be traversed directly with for-each; keySet(), values() or entrySet() are used instead.
Multiple Choice · Collections Framework
Question 2: Generic Declaration
Which of the following lines compiles?
B: A type argument must be a reference type: int must be replaced by the wrapper Integer (A: unexpected type); int values are boxed automatically. The diamond <> is written only on the new side (C). List is an interface and cannot be instantiated (D: List is abstract; cannot be instantiated).
Step-by-Step Trace · Lists
Question 3: ArrayList Operations
How does the list look after each operation? What does the program print? Note the difference between remove(2) and remove(Integer.valueOf(10)).
The three add calls place the elements at the end in insertion order; int values are boxed into Integer.
add(1, 15) inserts at index 1; 20 and 30 shift one position to the right.
The argument is an int, so remove(int index) runs: the element at index 2, 20 is removed, and 30 shifts left.
Integer.valueOf(10) is an object: remove(Object) removes the element whose value is 10.
set does not change the size; it replaces the value at index 0.
30 is at index 1; size is 2.
List<Integer> l = new ArrayList<>();
l.add(10);
l.add(20);
l.add(30);
l.add(1, 15);
l.remove(2);
l.remove(Integer.valueOf(10));
l.set(0, 99);
System.out.println(l + " " + l.indexOf(30)
+ " " + l.size());Multiple Choice · Lists
Question 4: Adding at the Front
Elements will be added to the front of a list one by one, 100,000 times: list.add(0, x). Which statement is true?
D: ArrayList uses an array internally: every insertion at the front shifts all elements one place to the right, O(n); total O(n²). LinkedList only links the new node to the head node, O(1); there is no shifting (C). The same interface offers the same methods, not the same cost (B). For operations at both ends, ArrayDeque is also suitable.
Output Question · Lists
Question 5: Stack
What does the program print?
Stack<Integer> y = new Stack<>();
y.push(4);
y.push(7);
y.push(1);
System.out.println(y.peek() + " " + y.search(4));
y.push(y.pop() + y.pop());
System.out.println(y + " " + y.size());Show answer
1 3 [4, 8] 2
peek() returns the top element (1) without removing it. search counts the position from 1 starting at the top: 1 → 1, 7 → 2, 4 → 3.
The first pop() removes 1, the second removes 7; the Integer values are added (8) and pushed back. println prints the stack from bottom to top: [4, 8].
Step-by-Step Trace · Queues
Question 6: ArrayDeque: Two Ends
A double-ended queue is used from both ends. What are the elements from head to tail after each operation, and what does the program print?
5 is added to the empty deque; the single element is both head and tail.
addFirst adds at the head.
Stack operations work at the head end: push adds at the head.
The queue operation offer adds at the tail.
pollLast removes and returns the last element: a = 7.
pop removes the first element: b = 2.
peekLast reads the last element 5 without removing it; offerFirst adds it at the head. A deque allows duplicate elements.
The deque is printed from head to tail; size is 3.
Deque<Integer> d = new ArrayDeque<>(); d.addLast(5); d.addFirst(8); d.push(2); d.offer(7); int a = d.pollLast(); int b = d.pop(); d.offerFirst(d.peekLast()); System.out.println(d + " " + a + " " + b + " " + d.size());
Multiple Choice · Queues
Question 7: Empty Queue
An empty Queue<String> k = new LinkedList<>(); — which statement is true?
A: Queue offers each operation in two forms: add/remove/element throw an exception on failure, offer/poll/peek return a special value (false/null). On an empty queue, remove() and element() throw NoSuchElementException.
Output Question · Queues
Question 8: PriorityQueue
What does the program print?
PriorityQueue<Integer> pq =
new PriorityQueue<>();
for (int x : new int[]{5, 1, 4, 1, 3}) {
pq.add(x);
}
System.out.println(pq.poll() + " " + pq.peek()
+ " " + pq.size());
pq.add(2);
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) {
sb.append(pq.poll()).append(' ');
}
System.out.println(sb);Show answer
1 1 4 1 2 3 4 5
A priority queue looks at the value, not the insertion order: poll always removes the smallest. A queue is not a set; both 1s stay. The first poll removes one 1, peek sees the other 1, size 4.
The 2 added later also goes to the right place; the draining order is from smallest to largest. println(pq) would print the unsorted internal heap layout.
Output Question · Sets
Question 9: LinkedHashSet and TreeSet
What does the program print?
String[] k = {"cherry", "Apple", "pear",
"apple", "Cherry", "pear"};
List<String> list = Arrays.asList(k);
Set<String> l = new LinkedHashSet<>(list);
Set<String> t = new TreeSet<>(list);
System.out.println(l.size() + " " + l);
System.out.println(t);Show answer
5 [cherry, Apple, pear, apple, Cherry] [Apple, Cherry, apple, cherry, pear]
Only the second "pear" is a duplicate; "Apple" and "apple" are different strings. LinkedHashSet keeps the insertion order.
TreeSet sorts strings in natural order (character code): uppercase letters (A = 65, C = 67) come before lowercase letters (a = 97). For alphabetical order, pass String.CASE_INSENSITIVE_ORDER or, for Turkish, pass Collator.
Output Question · Sets
Question 10: TreeSet Ranges
What does the program print?
TreeSet<Integer> t = new TreeSet<>( Arrays.asList(40, 10, 30, 20, 50, 30)); System.out.println(t.size() + " " + t.first() + " " + t.last()); System.out.println(t.headSet(30) + " " + t.tailSet(30) + " " + t.subSet(15, 45)); Set<Integer> k = new TreeSet<>(t); k.retainAll(Arrays.asList(20, 30, 60)); System.out.println(k + " " + t.add(60) + " " + t.add(60));
Show answer
5 10 50 [10, 20] [30, 40, 50] [20, 30, 40] [20, 30] true false
- The second 30 is not added: 5 elements, sorted.
headSet(30)contains the smaller elements, excluding 30;tailSet(30)contains the larger ones, including 30;subSet(15, 45)the interval [15, 45).retainAllkeeps the intersection (60 is not in the set). Since it works on a copy,tdoes not change.addreturns true if it added the element, false if it was already present.
Step-by-Step Trace · Maps
Question 11: Word Counting
What does the map contain after each word? What does the program print?
An empty TreeMap: keys are always kept sorted.
"su" is missing: getOrDefault gives 0, and 1 is written.
"çay" is missing: 1 is written. Since "ç" (231) is greater than "s" (115), it sorts after "su".
"su" exists: 1 + 1 = 2.
"kahve" is missing: getOrDefault gives 0, and 1 is written.
"çay" exists: 1 + 1 = 2.
"su" exists: 2 + 1 = 3.
The output is not in Turkish alphabetical order: String comparison looks at character codes.
String text = "su çay su kahve çay su"; Map<String, Integer> counts =new TreeMap<>(); for (String k : text.split(" ")) { counts.put(k, counts.getOrDefault(k, 0) + 1); } System.out.println(counts);
Multiple Choice · Maps
Question 12: The Return Value of put
What does the program print?
Map<String, Integer> m = new HashMap<>();
System.out.println(m.put("a", 1) + " "
+ m.put("a", 2) + " "
+ m.get("b") + " " + m.size());D: The first put adds a new key and returns null because there was no previous value. The second put sets the value of the same key to 2 and returns the old value (1). For a missing key, get gives null (not 0). Keys are unique: size 1.
Spot the Bug · Iterator
Question 13: Removing While Iterating
The code was written to remove even numbers from a list. What happens when it runs? Fix it using Iterator.
List<Integer> numbers = new ArrayList<>( Arrays.asList(4, 7, 10, 13, 16)); for (Integer s : numbers) { if (s % 2 == 0) { numbers.remove(s); } } System.out.println(numbers);
Show answer
Exception in thread "main" java.util.ConcurrentModificationException
4 is removed; at the following next() call, the iterator behind the for-each notices that the list was modified directly through a list method, not through the iterator, and throws an exception. println is never reached.
Iterator<Integer> it = numbers.iterator(); while (it.hasNext()) { if (it.next() % 2 == 0) { it.remove(); } } System.out.println(numbers); // [7, 13]
it.remove() safely removes the element obtained by the last next(). Java 8+: numbers.removeIf(s -> s % 2 == 0);
Multiple Choice · Iterator
Question 14: Iterator.remove
What happens if, on a freshly obtained iterator, it.next() is never called and then it.remove() is called?
C: remove() removes the element returned by the last next(); if there is no such element (next was never called, or remove was called a second time for the same element), IllegalStateException is thrown. NoSuchElementException occurs when no element is left and next() is called.
Output Question · Algorithms
Question 15: Collections Algorithms
What does the program print?
List<Integer> l = new ArrayList<>(
Arrays.asList(8, 3, 11, 5, 3));
Collections.sort(l);
System.out.println(l + " "
+ Collections.binarySearch(l, 8) + " "
+ Collections.binarySearch(l, 6));
Collections.reverse(l);
Collections.swap(l, 0, 4);
System.out.println(l + " "
+ Collections.frequency(l, 3) + " "
+ Collections.max(l));Show answer
[3, 3, 5, 8, 11] 3 -4 [3, 8, 5, 3, 11] 2 11
binarySearch works on a sorted list: 8 is at index 3. 6 is absent; the place where it should be inserted is index 3, so the return value is −(3) − 1 = −4. A negative result means "not found" and also carries the insertion point.
reverse → [11, 8, 5, 3, 3]; swap(l, 0, 4) swaps the ends → [3, 8, 5, 3, 11]. 3 occurs twice; the largest is 11.
Multiple Choice · Algorithms
Question 16: Order with compareTo
Collections.sort(students) — what is printed afterwards?
class Student implements Comparable<Student> { String name; int score; Student(String name, int score) { this.name = name; this.score = score; } public int compareTo(Student other) { return Integer.compare(other.score, score); } public String toString() { return name + ":" + score; } } // added: Cem:72, Ayse:95, Banu:60
B: Integer.compare(other.score, score) reverses the comparison: it returns a negative value for the one with the higher score, so that one comes first. The natural order is descending score. A is ascending order (Integer.compare(score, other.score)); C is order by name.
Output Question · Streams API
Question 17: Lazy Stream Pipeline
What does the program print? Does filter run for Ece and Burak?
List<String> names = Arrays.asList(
"Ali", "Zeynep", "Can", "Ece", "Burak");
Stream<String> s = names.stream()
.filter(a -> {
System.out.println("f " + a);
return a.length() == 3;
})
.map(a -> a.toUpperCase(Locale.ROOT));
System.out.println("ready");
System.out.println(s.limit(2)
.collect(Collectors.toList()));Show answer
ready f Ali f Zeynep f Can [ALI, CAN]
Intermediate operations are lazy: no lambda runs while the pipeline is being built, so “ready” is printed first. collect runs the pipeline, the elements pass one at a time: Ali passes, Zeynep is filtered out, Can passes.
limit(2) stops pulling elements from the source once it has two: filter is never called for Ece and Burak. Locale.ROOT makes uppercase conversion locale-independent; the no-argument toUpperCase() would turn “i” into “İ” in the Turkish locale and give [ALİ, CAN].
Multiple Choice · Choosing
Question 18: Choosing the Right Structure
In an emergency room, patients will be called not in order of arrival but by their degree of urgency; the most urgent patient must be obtainable quickly at any moment, and several patients may have the same degree. Which is suitable?
A: PriorityQueue: poll always returns the highest-priority element; insertion and removal are O(log n). B sorts in O(n log n) on every call. C is arrival order (FIFO). In D, two patients that compare as equal are treated as the same element, and the second one is not added to the set.