CCNA Arrays Collections Questions

72 of 86 questions · Page 1/2 · Arrays Collections topic · Answers revealed

1
MCQmedium

An application needs to maintain a set of unique customer IDs (type String) and frequently check if an ID is already present. The set is expected to contain up to 100,000 IDs. The current implementation uses a TreeSet, but performance tests show that the contains() operation is slower than desired. The developer considers switching to a HashSet. However, the business requires that when iterating the set, IDs must appear in sorted order. The developer proposes to convert the HashSet to a sorted list each time iteration is needed. Iteration occurs rarely (once per hour). What is the best approach?

A.Use ConcurrentSkipListSet
B.Use LinkedHashSet
C.Keep the TreeSet because it maintains sorted order
D.Use HashSet and sort when iteration is needed
AnswerD

Fast contains() and sorting once per hour is fine.

Why this answer

Option D is correct because the primary performance bottleneck is the contains() operation, which is O(log n) for TreeSet but O(1) average for HashSet. Since iteration with sorted order is required only once per hour, the cost of sorting the HashSet into a list (O(n log n)) is negligible compared to the frequent contains() checks. This trade-off optimizes for the dominant use case while still meeting the sorted iteration requirement.

Exam trap

The trap here is that candidates often assume sorted iteration must be maintained at all times, overlooking the fact that the requirement is only for rare iteration, making the conversion cost acceptable in exchange for faster contains().

How to eliminate wrong answers

Option A is wrong because ConcurrentSkipListSet is a thread-safe sorted set with O(log n) contains() performance, which does not improve over TreeSet and adds unnecessary concurrency overhead for a single-threaded scenario. Option B is wrong because LinkedHashSet maintains insertion order, not sorted order, so iterating it does not produce IDs in sorted order. Option C is wrong because keeping TreeSet retains the slower O(log n) contains() performance, which is the exact problem the developer is trying to solve.

2
MCQmedium

A developer is working on a high-performance trading application that processes market data. The system needs to maintain a sorted list of order IDs (Long values) that are frequently inserted and removed. The current implementation uses a TreeSet<Long> to store the order IDs. The application is experiencing performance degradation under high load, and profiling shows that the TreeSet operations are the bottleneck. The developer considers replacing the TreeSet with a data structure that offers O(log n) insertion and removal but also supports O(log n) indexed access (e.g., get by index) for batch processing. Which of the following should the developer choose to improve performance while maintaining the sorted order and adding indexed access?

A.No standard Java Collections class fulfills all requirements; consider a custom implementation.
B.Replace with TreeMap<Long, Boolean> and use the key set for iteration and indexed access via keySet().toArray().
C.Replace with PriorityQueue<Long> and use poll() for removal and toArray() for indexed access.
D.Replace with ArrayList<Long> and use Collections.sort() after each insertion.
AnswerA

No built-in collection provides O(log n) insertion, removal, and indexed access simultaneously.

Why this answer

Option A is correct because no standard Java Collections class provides O(log n) insertion, removal, and O(log n) indexed access while maintaining sorted order. TreeSet offers O(log n) insertion/removal but lacks indexed access; ArrayList provides O(1) indexed access but requires O(n log n) sorting after each insertion; PriorityQueue offers O(log n) insertion/removal but only O(1) peek access, not indexed access. A custom data structure like an order statistic tree (e.g., a balanced binary search tree with subtree sizes) is needed to meet all requirements.

Exam trap

The trap here is that candidates assume TreeSet or TreeMap can provide indexed access via toArray() or keySet(), overlooking that those operations are O(n) and defeat the purpose of O(log n) performance requirements.

How to eliminate wrong answers

Option B is wrong because TreeMap<Long, Boolean> does not provide O(log n) indexed access; keySet().toArray() requires O(n) time to copy all keys into an array, and the key set itself does not support get(index). Option C is wrong because PriorityQueue<Long> does not maintain a sorted list for indexed access; it only guarantees the head (minimum) element via O(1) peek, and toArray() returns elements in arbitrary order (heap order, not sorted). Option D is wrong because ArrayList<Long> with Collections.sort() after each insertion yields O(n log n) per insertion, which is worse than the O(log n) required, and does not maintain sorted order incrementally.

3
MCQeasy

Which of the following collections maintains elements in the order they were inserted?

A.LinkedHashSet
B.None of the above
C.PriorityQueue
D.HashSet
E.TreeSet
AnswerA

Correct: LinkedHashSet maintains insertion order.

Why this answer

LinkedHashSet maintains a doubly-linked list running through all of its entries, which defines the iteration ordering as the order in which elements were inserted into the set. This is specified in the Java documentation for LinkedHashSet, making it the only collection among the options that guarantees insertion order.

Exam trap

The trap here is that candidates often confuse 'ordered' (sorted) with 'ordered by insertion' and incorrectly choose TreeSet or PriorityQueue, forgetting that LinkedHashSet is the only standard Set implementation that preserves insertion order without sorting.

How to eliminate wrong answers

Option B is wrong because 'None of the above' is incorrect since LinkedHashSet does maintain insertion order. Option C is wrong because PriorityQueue orders elements according to their natural ordering or a provided Comparator, not by insertion order. Option D is wrong because HashSet uses hash-based storage and does not guarantee any specific order of elements.

Option E is wrong because TreeSet stores elements in sorted order (either natural ordering or by a Comparator), not in insertion order.

4
Multi-Selecthard

Which THREE statements are true about the java.util.Collection and java.util.stream.Stream APIs? (Choose three.)

Select 3 answers
A.The Collection.forEach() method is inherited from the Collection interface.
B.The Stream.forEach() operation processes elements in the encounter order of the stream only for sequential streams.
C.The Collection interface inherits the stream() method from the Iterable interface.
D.The Stream.toList() method returns an unmodifiable list.
E.The Iterator interface provides a default method forEachRemaining(Consumer<? super E> action).
AnswersB, D, E

Parallel streams may process elements out of order.

Why this answer

Option B is correct because the Stream.forEach() operation respects the encounter order of the stream only for sequential streams. For parallel streams, the order is not guaranteed unless the stream is explicitly forced to be sequential or uses forEachOrdered(). This behavior is defined in the Stream API specification.

Exam trap

The trap here is that candidates often assume forEach() always preserves order regardless of stream type, but the Stream API explicitly states that forEach() does not guarantee encounter order for parallel streams, unlike forEachOrdered().

5
MCQeasy

Given ArrayList<Integer> numbers = new ArrayList<>(List.of(1,2,3,4)); Which statement will insert element 10 at index 2?

A.numbers.add(10,2);
B.numbers.add(2,10);
C.numbers.set(2,10);
D.numbers.insert(2,10);
AnswerB

Inserts 10 at index 2, shifting subsequent elements to the right.

Why this answer

Option B is correct because the `ArrayList.add(int index, E element)` method inserts the specified element at the given index, shifting existing elements to the right. Here, `numbers.add(2,10)` inserts 10 at index 2, resulting in the list [1,2,10,3,4].

Exam trap

The trap here is that candidates often confuse the `add(index, element)` method with `set(index, element)`, mistakenly thinking both insert, or they reverse the argument order, expecting `add(element, index)` as in some other languages.

How to eliminate wrong answers

Option A is wrong because `add(10,2)` attempts to insert element 10 at index 2, but the arguments are reversed — the first argument must be the index, and the second the element, so this would cause a compile-time error or an `IndexOutOfBoundsException` if the index were valid. Option C is wrong because `set(2,10)` replaces the element at index 2 with 10, not inserts a new element, so the list size remains 4 and the original element at index 2 is lost. Option D is wrong because `ArrayList` has no `insert` method; this would cause a compile-time error.

6
MCQhard

You are developing a high-frequency trading application that processes a stream of market data ticks. Each tick is an immutable object containing timestamp, price, and volume. The ticks arrive in real time and must be stored in a collection for later analysis. The collection is accessed by multiple threads: one producer thread adds ticks, and multiple consumer threads periodically iterate to compute moving averages. The system must minimize latency for the producer and ensure that consumers see a consistent snapshot of data without interfering with ongoing writes. You initially used a synchronized ArrayList, but profiler results show high contention and poor throughput. You consider the following approaches. Which one best addresses the requirements?

A.Replace ArrayList with CopyOnWriteArrayList, which provides thread-safety without explicit synchronization and allows concurrent iteration while modifications occur.
B.Use a ConcurrentLinkedDeque for writes and have consumers obtain a consistent snapshot by calling toArray() on the deque. The toArray() operation is O(n) but provides a point-in-time view without blocking the producer.
C.Use a ConcurrentLinkedDeque and have consumers acquire a read lock when iterating, while the producer uses a write lock. This provides fine-grained locking and reduces contention.
D.Maintain two synchronized ArrayLists. The producer writes to one list while consumers read from the other. Periodically, swap references using an AtomicReference. This allows lock-free reads after the swap.
AnswerB

ConcurrentLinkedDeque offers lock-free, low-latency writes for the producer. Calling toArray() creates a snapshot that is consistent as of the moment of the call, allowing consumers to iterate without interference. The O(n) cost of toArray() is acceptable if consumers iterate infrequently relative to the number of writes.

Why this answer

Option B is correct because ConcurrentLinkedDeque allows lock-free, non-blocking writes (ideal for low-latency producers) and calling toArray() provides a consistent, immutable snapshot of the deque at that instant without blocking concurrent modifications. This satisfies the requirement for multiple consumers to see a consistent view while the producer continues writing with minimal latency.

Exam trap

The trap here is that candidates often assume CopyOnWriteArrayList is the best choice for concurrent reads and writes, but they overlook its write-cost penalty, which is disastrous for high-frequency producers; the correct solution uses a non-blocking collection with a snapshot mechanism.

How to eliminate wrong answers

Option A is wrong because CopyOnWriteArrayList creates a new copy of the underlying array on every write operation, which incurs O(n) copy cost and high memory overhead, making it unsuitable for a high-frequency producer that must minimize latency. Option C is wrong because ConcurrentLinkedDeque does not support read/write locks; it is designed for non-blocking, lock-free concurrency, and adding explicit locks would reintroduce contention and defeat its purpose. Option D is wrong because maintaining two synchronized ArrayLists with periodic swapping introduces complexity, potential staleness, and still requires synchronization on writes, which does not eliminate the contention problem shown in the profiler.

7
Multi-Selectmedium

Which TWO statements are true about creating an unmodifiable List?

Select 2 answers
A.Collections.unmodifiableList() returns a view that is unmodifiable, but the backing list can still be changed.
B.List.of() returns an immutable list that does not support any modification.
C.List.copyOf() creates a list that, if the source list is changed, the copy also changes.
D.new ArrayList<>(Arrays.asList(...)) creates an unmodifiable list.
E.Arrays.asList() returns an unmodifiable list.
AnswersA, B

View is unmodifiable, backing list change reflected.

Why this answer

B and D are correct. B: Collections.unmodifiableList returns a view that throws UnsupportedOperationException on mutating operations; it does not prevent changes to backing list. D: List.of creates an immutable list; the backing is not modifiable.

A is wrong because Arrays.asList returns a fixed-size but modifiable list (set allowed). C is wrong because new ArrayList is mutable. E is wrong because List.copyOf creates an immutable copy, but changing original does not affect the copy? Actually copyOf is independent, so modifications to original do not affect the copy; however the statement says 'does not guarantee immutability' which is false because the copy is immutable.

So E is false.

8
MCQmedium

Which of the following correctly sorts an array of integers (int[] arr) in descending order?

A.Integer[] boxed = Arrays.stream(arr).boxed().toArray(Integer[]::new); Arrays.sort(boxed, Collections.reverseOrder()); arr = Arrays.stream(boxed).mapToInt(i->i).toArray();
B.Arrays.sort(arr, Collections.reverseOrder());
C.None of the above, because primitive arrays cannot be sorted in descending order.
D.Arrays.sort(arr, (a,b) -> b - a);
E.Arrays.parallelSort(arr, (a,b) -> b - a);
AnswerA

Correct: this boxes the array, sorts descending, and unboxes back to int[].

Why this answer

Option A is correct because it demonstrates the proper technique for sorting a primitive int array in descending order. The `Arrays.sort()` method does not accept a `Comparator` for primitive arrays, so the array must first be boxed into an `Integer[]` using `Arrays.stream(arr).boxed().toArray(Integer[]::new)`. After sorting with `Collections.reverseOrder()`, the result is unboxed back to `int[]` via `mapToInt(i->i).toArray()`.

This approach correctly leverages the `Comparator` interface, which only works with object types.

Exam trap

The trap here is that candidates often assume `Arrays.sort()` with a `Comparator` works on primitive arrays, but the Java API explicitly separates primitive and object array sorting, and the `Comparator` overload is only available for object arrays.

How to eliminate wrong answers

Option B is wrong because `Arrays.sort()` for a primitive `int[]` does not accept a `Comparator`; the overload `sort(T[], Comparator)` only works with object arrays. Option C is wrong because primitive arrays can be sorted in descending order using the boxing technique shown in option A, so the claim is false. Option D is wrong because `Arrays.sort(int[], Comparator)` does not exist; the lambda `(a,b) -> b - a` would require a `Comparator<Integer>`, which cannot be applied to a primitive array.

Option E is wrong for the same reason as D — `Arrays.parallelSort(int[], Comparator)` is not a valid overload for primitive arrays.

9
MCQeasy

A developer is implementing a cache that stores recent user sessions. The cache should maintain the most recently accessed session at the end, and when the cache reaches its maximum size (1000), it should remove the least recently accessed session (i.e., the oldest). The developer chooses a LinkedList to store sessions, adding new sessions at the end and removing from the front. However, performance is poor because searching for an existing session to update its position requires O(n) linear scan. Which collection should replace the LinkedList to improve performance while maintaining the removal order?

A.TreeSet
B.HashSet
C.LinkedHashSet
D.ArrayList
AnswerC

O(1) add, remove, contains; maintains insertion order; can reinsert to move to end.

Why this answer

LinkedHashSet (C) maintains insertion order (which can be used to represent access order if reinserted on access) and provides O(1) average-time complexity for add, remove, and contains operations. By removing and re-adding a session upon access, it moves to the end, and the oldest (first inserted) can be removed from the front when the size exceeds 1000, solving the O(n) scan problem of LinkedList.

Exam trap

The trap here is that candidates often choose HashSet for speed but forget that order is required, or choose TreeSet thinking sorted order helps, but neither maintains insertion/access order for LRU eviction.

How to eliminate wrong answers

Option A is wrong because TreeSet orders elements by their natural ordering or a comparator, not by insertion or access order, and does not allow duplicates; it would not maintain the required removal order (oldest first) and has O(log n) operations. Option B is wrong because HashSet does not maintain any order; it cannot guarantee that the least recently accessed session (oldest) is at the front for removal. Option D is wrong because ArrayList provides O(n) removal from the front (due to shifting elements) and O(n) search for an existing session, offering no performance improvement over LinkedList.

10
Multi-Selecthard

Which TWO are true about the PriorityQueue class?

Select 2 answers
A.It allows null elements.
B.It orders elements based on insertion order.
C.It is not thread-safe.
D.It can be used with a custom Comparator.
E.It provides O(1) time for contains().
AnswersC, D

Correct, not synchronized.

Why this answer

Option C is correct because PriorityQueue is not thread-safe; it does not synchronize access, so concurrent modifications without external synchronization can lead to inconsistent behavior. Option D is correct because PriorityQueue can accept a custom Comparator at construction time to define the ordering of elements, overriding the natural order.

Exam trap

The trap here is that candidates often confuse PriorityQueue with a FIFO queue (like LinkedList) and assume insertion order, or mistakenly think it allows nulls or provides O(1) contains() due to its heap structure.

11
MCQhard

A Java 17 application uses a HashMap<Integer, List<String>> to group error messages by error code. The map may contain up to 5000 error codes, and each list may contain up to 1000 messages. The application frequently retrieves the list for a given error code and iterates over it. The lists are rarely modified after initial population. The current performance is acceptable, but the team wants to reduce memory footprint. The developer suggests replacing the inner List<String> with an array (String[]), but then iteration would require conversion. Another developer suggests using a TreeMap instead of HashMap to save memory because TreeMap uses less memory per entry? Actually TreeMap has more overhead. Actually HashMap typically has lower overhead than TreeMap. The correct approach: Since lists are rarely modified, consider using List.of to create immutable lists that can be shared? Or use ArrayList with initial capacity to reduce resizing. But the stem says 'reduce memory footprint'. Option C: Use ArrayList with initial capacity to reduce internal array resizing overhead. Option A: Use TreeMap - wrong because TreeMap uses more memory per entry due to tree nodes. Option B: Use array of arrays - not type-safe. Option D: Use LinkedList - higher memory overhead per element. So best is to use ArrayList with proper sizing to minimize wasted space.

A.Replace ArrayList<String> with LinkedList<String>
B.Replace HashMap with TreeMap
C.Replace List<String> with String[]
D.Use ArrayList<String> with initial capacity set to expected list size
AnswerD

Minimizes internal array resizing and waste.

Why this answer

Option D is correct because using an ArrayList with an initial capacity set to the expected list size eliminates the overhead of repeated internal array resizing (which wastes memory by leaving unused capacity). Since the lists are rarely modified after initial population, this approach minimizes wasted space without sacrificing iteration performance, unlike the other options.

Exam trap

The trap here is that candidates assume switching to a different collection type (like TreeMap or LinkedList) will save memory, when in fact the most effective memory optimization is to eliminate wasted internal capacity by using ArrayList with a proper initial capacity.

How to eliminate wrong answers

Option A is wrong because LinkedList has higher per-element memory overhead (due to node objects storing prev/next pointers) and poor iteration performance, increasing memory footprint. Option B is wrong because TreeMap uses more memory per entry than HashMap (tree nodes store color, parent, left, right pointers) and offers no memory benefit. Option C is wrong because replacing List<String> with String[] would require manual conversion for iteration, losing type safety and flexibility, and does not inherently reduce memory if the array is oversized; the real memory waste comes from unused capacity, not the collection type.

12
Multi-Selectmedium

Which THREE of the following are valid ways to create a new ArrayList<Integer>? (Select three.)

Select 3 answers
A.new ArrayList<>(Arrays.asList(1,2,3))
B.new ArrayList<>(10, 20, 30)
C.new ArrayList<>(List.of(1,2,3))
D.(ArrayList<Integer>) Arrays.asList(1,2,3)
E.new ArrayList<Integer>() with initial capacity 10
AnswersA, C, E

Creates an ArrayList from the List returned by Arrays.asList.

Why this answer

Option A is correct because `Arrays.asList(1,2,3)` returns a fixed-size `List<Integer>`, and passing it to the `ArrayList` constructor creates a new, mutable `ArrayList<Integer>` containing the same elements. This is a standard way to initialize an `ArrayList` with known values.

Exam trap

The trap here is that candidates confuse `Arrays.asList` with `ArrayList` and attempt to cast the returned list directly, not realizing it is a different class that cannot be cast to `ArrayList`.

13
Multi-Selectmedium

Which TWO of the following statements about the Collections framework are true?

Select 2 answers
A.Collections.checkedList performs type checking at compile time.
B.Collections.unmodifiableList returns an unmodifiable view of the list.
C.List.of returns a mutable list.
D.Collections.synchronizedList returns a thread-safe list.
E.Arrays.asList returns a mutable list of variable size.
AnswersB, D

Correct: it wraps the list to prevent modifications.

Why this answer

Option B is correct because `Collections.unmodifiableList()` returns a view of the specified list that cannot be modified. Any attempt to modify the returned list (e.g., add, remove, set) will throw an `UnsupportedOperationException`. This is a standard method in the Java Collections Framework to provide read-only access to a list.

Exam trap

The trap here is that candidates often confuse `Collections.unmodifiableList()` with `List.of()` or assume that `Arrays.asList()` returns a fully mutable list of variable size, when in fact it returns a fixed-size list backed by the array.

14
MCQeasy

What is the result of the following code? List<String> list = List.of("A", "B"); list.add("C"); System.out.println(list);

A.[A, B, C]
B.[A, B]
C.An exception is thrown at runtime
D.Compilation error
AnswerC

UnsupportedOperationException thrown.

Why this answer

The `List.of()` factory method returns an immutable list. Calling `add()` on an immutable list throws an `UnsupportedOperationException` at runtime, so the code does not compile or run successfully. Option C is correct because the exception is thrown when the `add` method is invoked.

Exam trap

The trap here is that candidates often assume `List.of()` returns a regular mutable `ArrayList` or that the code will simply ignore the `add` call, but the exam tests the specific runtime exception behavior of immutable collections created by factory methods.

How to eliminate wrong answers

Option A is wrong because it assumes the list is mutable and that 'C' can be added, but `List.of()` creates an immutable list that cannot be modified. Option B is wrong because it suggests the list remains unchanged and the program prints '[A, B]', but the `add` call throws an exception before the `println` executes. Option D is wrong because there is no compilation error; the code compiles fine since `add()` is a valid method on the `List` interface, but it fails at runtime.

15
MCQmedium

A developer is implementing a custom sort for a list of Employee objects. The Employee class has fields: String name, int age. The list must be sorted first by name (ascending, case-insensitive), then by age (descending). Which Comparator implementation correctly achieves this?

A.Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER).thenComparingInt(Employee::getAge)
B.Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER).thenComparing(Comparator.comparingInt(Employee::getAge).reversed())
C.Comparator.comparingInt(Employee::getAge).reversed().thenComparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)
D.Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge).reversed()
AnswerB

Correctly sorts by name case-insensitive ascending, then age descending.

Why this answer

Option B is correct because it first sorts by name using a case-insensitive comparator, then chains a reversed comparator for age, ensuring descending order for age while preserving the primary sort by name. The `thenComparing` method correctly applies the reversed age comparator as a secondary sort, which is essential for multi-field sorting where one field requires descending order.

Exam trap

The trap here is that candidates often forget to reverse only the secondary comparator (age) and instead apply `reversed()` to the entire chain, which inverts all sort orders, or they mistakenly use `thenComparingInt` without reversal, leading to ascending age order.

How to eliminate wrong answers

Option A is wrong because `thenComparingInt(Employee::getAge)` sorts age in ascending order, not descending as required. Option C is wrong because it sorts by age first (descending) and then by name, which reverses the required primary and secondary sort order. Option D is wrong because `reversed()` is applied to the entire comparator chain, reversing both the name sort (to descending) and the age sort (to ascending), which does not meet the requirement of ascending name and descending age.

16
Multi-Selecthard

Which TWO statements about the java.util.Collections class are true?

Select 2 answers
A.Collections.sort(List) returns a new sorted list.
B.Collections.reverse(List) returns a new reversed list.
C.Collections.shuffle(List) returns a new shuffled list.
D.Collections.synchronizedList(List) returns a synchronized list backed by the specified list.
E.Collections.unmodifiableList(List) returns an unmodifiable view of the specified list.
AnswersD, E

It returns a thread-safe list backed by the specified list.

Why this answer

Option D is correct because Collections.synchronizedList(List) returns a synchronized (thread-safe) list backed by the specified list. This method wraps the provided list in a synchronized wrapper, ensuring that all access to the underlying list is serialized when accessed through the returned list. It does not create a new independent list but provides a view that synchronizes all method calls.

Exam trap

The trap here is that candidates often confuse mutating methods like sort, reverse, and shuffle with methods that return new collections, when in fact these methods modify the list in place and return void, whereas synchronizedList and unmodifiableList return wrapper views.

17
MCQmedium

Consider: List<String> list = Arrays.asList("A", "B", "C"); list.add("D"); What is the result?

A.An ArrayIndexOutOfBoundsException is thrown
B.The list becomes [A, B, C, D]
C.A ClassCastException is thrown
D.An UnsupportedOperationException is thrown
AnswerD

Arrays.asList returns fixed-size list.

Why this answer

The `Arrays.asList()` method returns a fixed-size list backed by the specified array. This list does not support structural modification operations like `add()` or `remove()`. Calling `add()` on such a list throws an `UnsupportedOperationException` at runtime.

Exam trap

The trap here is that candidates confuse `Arrays.asList()` with `new ArrayList<>(Arrays.asList(...))`, assuming the returned list is a regular mutable `ArrayList`, but the exam tests the fixed-size behavior of the wrapper list.

How to eliminate wrong answers

Option A is wrong because `ArrayIndexOutOfBoundsException` would occur only when accessing an invalid index in an array or list, not when calling `add()` on a fixed-size list. Option B is wrong because the list returned by `Arrays.asList()` is immutable in size, so `add()` cannot modify it to become [A, B, C, D]. Option C is wrong because `ClassCastException` is thrown when an object is cast to an incompatible type, which is not relevant here; the exception type is `UnsupportedOperationException`.

18
MCQhard

Which statement about Collection interface remove methods is correct?

A.Collection.remove(Object) removes the first occurrence and returns boolean.
B.List.remove(int) removes element at index and returns the removed element.
C.Collection.remove(Object) removes all occurrences of the element.
D.Both B and C
AnswerA

Correct behavior for remove method in Collection.

Why this answer

The correct answer is A because the Collection interface's remove(Object) method removes the first occurrence of the specified element from the collection, if present, and returns true if the collection was modified (i.e., the element was found and removed). This behavior is defined in the Java Collections Framework and applies to all implementations of Collection, such as ArrayList and HashSet.

Exam trap

The trap here is that candidates often confuse the Collection interface's remove(Object) with the List interface's remove(int), mistakenly thinking that remove(Object) removes all occurrences or that the index-based remove is part of the Collection interface.

How to eliminate wrong answers

Option B is wrong because List.remove(int) is not a method of the Collection interface; it is a method specific to the List interface, and while it does remove the element at the specified index and return the removed element, the question asks about the Collection interface, not List. Option C is wrong because Collection.remove(Object) removes only the first occurrence of the element, not all occurrences; to remove all occurrences, one would typically use removeAll or a loop with remove. Option D is wrong because it combines both B and C, both of which are incorrect in the context of the Collection interface.

19
Multi-Selecteasy

Which THREE are valid ways to iterate over a Map<String, Integer>?

Select 3 answers
A.for (Map.Entry<String, Integer> entry : map) { }
B.for (String key : map.keySet()) { }
C.map.forEach((k, v) -> { });
D.for (Integer value : map.values()) { }
E.for (Map.Entry<String, Integer> entry : map.entrySet()) { }
AnswersB, C, E

Valid.

Why this answer

Option B is correct because `Map.keySet()` returns a `Set<String>` containing all keys, which can be iterated using an enhanced for-each loop. This is a standard way to access keys in a `Map<String, Integer>`.

Exam trap

The trap here is that candidates may think `Map` itself is iterable (like `Collection`), but it is not; you must use `keySet()`, `values()`, or `entrySet()` to obtain an iterable view, and `forEach` is a default method on `Map` that works directly.

20
Multi-Selectmedium

Which TWO are valid ways to create an immutable List in Java?

Select 2 answers
A.Stream.of("a").collect(Collectors.toList())
B.Collections.unmodifiableList(new ArrayList<>())
C.Arrays.asList("a", "b")
D.new ArrayList<>()
E.List.of("a", "b")
AnswersB, E

Returns immutable view.

Why this answer

Option B is correct because `Collections.unmodifiableList()` returns a view of the specified list that cannot be structurally modified; any attempt to add, remove, or set elements will throw an `UnsupportedOperationException`. Option E is correct because `List.of()` (introduced in Java 9) directly creates an immutable list that disallows `null` elements and throws `UnsupportedOperationException` on mutation attempts.

Exam trap

The trap here is that candidates often confuse 'fixed-size' (as in `Arrays.asList()`) with 'immutable', or assume that `Collectors.toList()` returns an immutable list, when in fact it returns a mutable `ArrayList`.

21
MCQeasy

A developer writes the following code using Java 17: List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add(10); What is the result?

A.Compilation error
B.The code compiles and runs successfully
C.ClassCastException at runtime
D.Compiler warning, but runs with unchecked operation
AnswerA

Generics prevent adding an Integer to List<String>.

Why this answer

Option A is correct because the code attempts to add an integer (10) to a `List<String>`, which is a compile-time type mismatch. Java's generics enforce type safety at compile time, so adding an `int` (autoboxed to `Integer`) to a `List<String>` results in a compilation error. The code will not compile, and no runtime execution occurs.

Exam trap

The trap here is that candidates may mistakenly think autoboxing or runtime type erasure will allow the code to compile with a warning, but Java 17's strict generic type checking enforces a compilation error for such mismatches.

How to eliminate wrong answers

Option B is wrong because the code does not compile due to the type mismatch, so it cannot run successfully. Option C is wrong because a `ClassCastException` would only occur at runtime if the code compiled with unchecked operations (e.g., raw types), but here the compiler rejects the code outright. Option D is wrong because the compiler does not issue a warning for this code; it produces a hard compilation error, not an unchecked warning, since the type mismatch is detected statically.

22
Matchingmedium

Match each Java collection class to its underlying data structure.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Resizable array

Doubly linked list

Hash table

Red-black tree

Hash table with buckets

Why these pairings

Each collection class uses a specific data structure for storage.

23
MCQhard

Which statement about TreeSet is true when using a custom Comparator that does not define equals() consistently with compare()?

A.TreeSet uses equals() to determine duplicates.
B.TreeSet uses hashCode() for ordering.
C.TreeSet considers two elements equal if the comparator returns 0.
D.TreeSet throws IllegalArgumentException if equals() is inconsistent.
AnswerC

Set uses comparator's compare method.

Why this answer

TreeSet uses the compare() method of the provided Comparator (or the natural ordering's compareTo()) to determine element equality. When a custom Comparator returns 0 for two elements, TreeSet treats them as duplicates and does not add the second element, regardless of what equals() returns. This is specified in the Java Collections Framework documentation and is critical for maintaining the Set contract.

Exam trap

The trap here is that candidates often assume TreeSet uses equals() for duplicate detection because of the general Set contract, but TreeSet (and TreeMap) specifically override that behavior to use compare()/compareTo() instead.

How to eliminate wrong answers

Option A is wrong because TreeSet does not use equals() to determine duplicates; it relies on the Comparator's compare() method (or Comparable's compareTo()) returning 0. Option B is wrong because TreeSet uses the Comparator's compare() method for ordering, not hashCode(); hashCode() is used by HashSet, not TreeSet. Option D is wrong because TreeSet does not throw an IllegalArgumentException when equals() is inconsistent with compare(); it simply ignores equals() and uses compare() for both ordering and duplicate detection.

24
Multi-Selectmedium

Which TWO statements about Arrays.asList() are true? (Select two.)

Select 2 answers
A.It supports adding and removing elements.
B.It returns a new ArrayList with a copy of the elements.
C.It can be used to convert an array to a mutable list if wrapped with new ArrayList<>().
D.It returns a fixed-size list backed by the original array.
E.Changes to the returned list are reflected in the original array.
AnswersD, E

The returned list size is fixed and changes to the list are reflected in the array.

Why this answer

Option D is correct because `Arrays.asList()` returns a fixed-size list backed by the original array, meaning the list's size cannot be changed (no add or remove operations allowed). Option E is correct because any modification to the returned list (e.g., setting an element) directly modifies the underlying array, and vice versa, as the list is a view of the array.

Exam trap

The trap here is that candidates often assume `Arrays.asList()` returns a regular `java.util.ArrayList` and therefore supports add/remove, or they forget that the returned list is fixed-size and backed by the original array, leading them to select options A or B.

25
MCQhard

Which of the following correctly describes the behavior of the following code? List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); for (String s : list) { if (s.equals("A")) { list.remove(s); } } System.out.println(list);

A.ConcurrentModificationException is thrown
B.Compilation error
C.[B]
D.[A, B] unchanged
AnswerA

Fail-fast behavior.

Why this answer

The code uses an enhanced for-each loop to iterate over an ArrayList while calling `list.remove(s)` when the element equals "A". This modifies the list structurally during iteration, which causes the iterator (used internally by the for-each loop) to detect the concurrent modification and throw a `ConcurrentModificationException` at runtime. The exception is thrown because the iterator's `modCount` check fails when the list is modified outside of the iterator's own `remove` method.

Exam trap

The trap here is that candidates often think the for-each loop will safely remove the element and continue, or that the exception only occurs with multiple threads, but in fact any structural modification (add, remove, clear) to the underlying collection during single-threaded iteration triggers the fail-fast mechanism.

How to eliminate wrong answers

Option B is wrong because the code compiles without error; the enhanced for-each loop and `ArrayList.remove()` are valid Java syntax. Option C is wrong because the output is not `[B]`; the exception is thrown before the loop completes, so no output is printed. Option D is wrong because the list is not unchanged; the structural modification triggers an exception, not a successful removal.

26
MCQmedium

Given: var list = List.of("A", "B", "C"); list.set(0, "Z"); What is the result?

A.An ArrayIndexOutOfBoundsException is thrown
B.An UnsupportedOperationException is thrown
C.The code does not compile because var cannot be used with List.of
D.The list is modified to [Z, B, C]
AnswerB

List.of returns an unmodifiable list.

Why this answer

The `List.of()` method returns an immutable list, meaning its elements cannot be added, removed, or replaced. Calling `set()` on an immutable list throws an `UnsupportedOperationException` at runtime, which is why option B is correct.

Exam trap

The trap here is that candidates often assume `List.of()` returns a mutable list similar to `new ArrayList<>()`, but it actually returns an immutable list, and the `set()` method will throw an `UnsupportedOperationException` at runtime.

How to eliminate wrong answers

Option A is wrong because `ArrayIndexOutOfBoundsException` occurs only when accessing an invalid index on a mutable array or list, but here the list is immutable and the exception type is different. Option C is wrong because `var` can be used with `List.of()`; the code compiles fine since the type is inferred as `List<String>`. Option D is wrong because the list is immutable and cannot be modified; the `set()` call throws an exception instead of changing the list.

27
MCQmedium

A developer writes: List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add(1, "C"); System.out.println(list); What is the output?

A.[A, C, B]
B.[A, B, C]
C.[A, B]
D.[C, A, B]
AnswerA

Correct insertion order.

Why this answer

The correct answer is A because the `add(int index, E element)` method inserts the element at the specified index, shifting subsequent elements to the right. Initially, the list is [A, B]. After `list.add(1, "C")`, "C" is inserted at index 1, moving "B" to index 2, resulting in [A, C, B].

Exam trap

The trap here is that candidates often confuse the `add(E element)` method (which appends at the end) with the `add(int index, E element)` method (which inserts at a specific index), leading them to mistakenly think "C" is appended or placed at the beginning.

How to eliminate wrong answers

Option B is wrong because it assumes the `add(int index, E element)` method appends the element at the end, but it actually inserts at the given index. Option C is wrong because it omits the inserted element "C", ignoring the effect of the `add` method. Option D is wrong because it places "C" at the beginning (index 0), but the insertion was at index 1, not index 0.

28
MCQhard

A developer creates an unmodifiable list via Collections.unmodifiableList(originalList). Later, originalList is modified by adding an element. Which statement is true?

A.The unmodifiable list remains unchanged
B.The unmodifiable list becomes inconsistent
C.An UnsupportedOperationException is thrown
D.The unmodifiable list reflects the addition
AnswerD

Unmodifiable wrapper is a view; changes to backing list are visible.

Why this answer

D is correct because `Collections.unmodifiableList()` returns a view-backed unmodifiable list that reflects any changes made to the original list. The unmodifiable list does not create a snapshot; it wraps the original list, so modifications to the original are visible through the unmodifiable wrapper.

Exam trap

The trap here is that candidates often assume `Collections.unmodifiableList()` creates an immutable copy, similar to `List.copyOf()`, but it actually creates a dynamic view that changes with the original list.

How to eliminate wrong answers

Option A is wrong because the unmodifiable list is a view of the original list, so it does change when the original list is modified. Option B is wrong because the unmodifiable list remains consistent with the original list; it does not become inconsistent. Option C is wrong because `UnsupportedOperationException` is thrown only when attempting to modify the unmodifiable list itself (e.g., calling `add()` on it), not when the original list is modified.

29
MCQhard

Which of the following will compile without error and produce an unmodifiable list containing three elements?

A.Arrays.asList("A","B","C")
B.new ArrayList<>(List.of("A","B","C"))
C.List.of("A","B","C")
D.Collections.unmodifiableList(new ArrayList<>(List.of("A","B","C")))
E.None of the above
AnswerC

Correct: List.of returns an immutable list.

Why this answer

Option C is correct because `List.of("A","B","C")` returns an unmodifiable list containing exactly three elements, as specified by the Java 9+ static factory method. It compiles without error and any attempt to modify the list will throw an `UnsupportedOperationException`.

Exam trap

The trap here is that candidates often confuse `Arrays.asList()` with an unmodifiable list, not realizing that `set()` is still permitted, while `List.of()` is truly immutable and the correct choice for an unmodifiable list in modern Java.

How to eliminate wrong answers

Option A is wrong because `Arrays.asList("A","B","C")` returns a fixed-size list backed by the array, but it is not truly unmodifiable — you can still call `set()` to change elements, so it does not produce an unmodifiable list. Option B is wrong because `new ArrayList<>(List.of("A","B","C"))` creates a mutable `ArrayList` that can be modified via `add()` or `remove()`, so it is not unmodifiable. Option D is wrong because `Collections.unmodifiableList(new ArrayList<>(List.of("A","B","C")))` does produce an unmodifiable view, but it is not the simplest or most direct way; the question asks for an option that 'will compile without error and produce an unmodifiable list', and while D technically works, it is not the best answer because it involves extra wrapping and the question implies a single method call.

Option E is wrong because option C is correct.

30
Multi-Selecthard

Which TWO are true about HashSet and TreeSet?

Select 2 answers
A.HashSet maintains elements in insertion order.
B.HashSet uses equals() and hashCode() for uniqueness, TreeSet uses compareTo() or Comparator.
C.Both implement the List interface.
D.Both guarantee constant-time performance for basic operations (add, remove, contains).
E.TreeSet requires elements to be mutually comparable, unless a Comparator is provided.
AnswersB, E

Correct.

Why this answer

Option B is correct because HashSet relies on the equals() and hashCode() methods to determine element uniqueness, while TreeSet uses the natural ordering (compareTo()) or a provided Comparator to maintain sorted order and check for duplicates. This distinction is fundamental to how these Set implementations enforce uniqueness.

Exam trap

The trap here is that candidates often confuse the performance guarantees of HashSet (constant-time average) with TreeSet (logarithmic time), or mistakenly think both maintain insertion order, when in fact only LinkedHashSet does.

31
MCQmedium

What does the following code print? List<Integer> list = new ArrayList<>(List.of(1,2,3)); list.replaceAll(x -> x * 2); System.out.println(list);

A.[2,3,4]
B.[2,4,6]
C.Compilation fails
D.[1,4,9]
E.[1,2,3]
AnswerB

Correct: each element is doubled.

Why this answer

The `replaceAll` method on a `List` applies the given `UnaryOperator` to each element, replacing it with the result. Here, `x -> x * 2` multiplies each integer by 2, so the list becomes `[2, 4, 6]`. Option B is correct because the code compiles and runs, producing that output.

Exam trap

The trap here is that candidates may think `replaceAll` doesn't exist on `List` or that it requires a `Comparator`, or they may confuse it with `replaceAll` on `Map` or `String`, leading them to incorrectly choose compilation failure (Option C).

How to eliminate wrong answers

Option A is wrong because it suggests the output is `[2,3,4]`, which would result from adding 1 to each element, not multiplying by 2. Option C is wrong because the code compiles successfully; `List.replaceAll` accepts a `UnaryOperator` lambda, and `List.of(1,2,3)` returns an immutable list, but `new ArrayList<>(List.of(1,2,3))` creates a mutable copy, so no compilation error occurs. Option D is wrong because it implies squaring each element (`x -> x * x`), not doubling.

Option E is wrong because it shows the original list unchanged, ignoring the effect of `replaceAll`.

32
MCQmedium

A web server logs user sessions. Each session has a unique session ID (String) and a last access time (long). The system needs to evict sessions that have been inactive for more than 30 minutes. The current implementation uses a HashMap<String, Long> to store session IDs and last access times. A scheduled task iterates over all entries and removes those where currentTime - lastAccess > 30 minutes. However, this iteration is becoming slow as the number of sessions grows (millions). The developer wants to improve the eviction performance without affecting the O(1) put and get operations. Which approach should be taken?

A.Use PriorityQueue<Session> ordered by last access time and update the time when accessed.
B.Use ConcurrentHashMap<String, Long> and use parallel streams to remove expired entries.
C.Use LinkedHashMap<String, Long> with access-order=true and override removeEldestEntry() to evict entries older than 30 minutes.
D.Use TreeMap<String, Long> sorted by last access time and poll the first entry if too old.
AnswerC

Efficiently maintains access order and automatically evicts eldest.

Why this answer

Option C is correct because LinkedHashMap with access-order=true and a custom removeEldestEntry() method provides O(1) amortized put/get operations while automatically evicting the least-recently accessed entry when a condition is met. By overriding removeEldestEntry() to check if the eldest entry's last access time is older than 30 minutes, the eviction happens during put operations without requiring a separate iteration over all entries, thus solving the performance issue.

Exam trap

The trap here is that candidates may think a sorted structure like TreeMap or PriorityQueue is needed for time-based eviction, but they overlook the O(1) access-time requirement and the fact that LinkedHashMap's access-order mode provides automatic LRU eviction without explicit iteration.

How to eliminate wrong answers

Option A is wrong because PriorityQueue does not support O(1) updates to the ordering key; updating the last access time would require removing and reinserting the element, which is O(log n) and disrupts the O(1) requirement for get operations. Option B is wrong because using parallel streams to iterate over a ConcurrentHashMap still requires scanning all entries, which is O(n) and does not improve the fundamental iteration cost; it also introduces thread-safety overhead without solving the algorithmic inefficiency. Option D is wrong because TreeMap maintains order by key (session ID), not by last access time; sorting by last access time would require a custom comparator that cannot be updated efficiently, and polling the first entry would not guarantee it is the oldest by access time.

33
MCQeasy

Examine the code: List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); for (String s : list) { list.remove(s); } What is the outcome?

A.A ConcurrentModificationException is thrown
B.The loop completes successfully and list becomes empty
C.An IllegalStateException is thrown
D.The loop completes successfully and list contains [B]
AnswerA

Modifying list during iteration with for-each throws exception.

Why this answer

The for-each loop internally uses an Iterator to traverse the list. When the list is structurally modified (via `list.remove()`) during iteration without using the iterator's own `remove()` method, the iterator detects a concurrent modification and throws a `ConcurrentModificationException`. This is a fail-fast behavior of the `ArrayList` iterator.

Exam trap

The trap here is that candidates often assume the for-each loop will safely remove elements one by one, not realizing that the implicit iterator throws an exception on structural modification.

How to eliminate wrong answers

Option B is wrong because the loop does not complete successfully; the exception is thrown before the list becomes empty. Option C is wrong because `IllegalStateException` is not thrown in this scenario; it is typically thrown when calling `remove()` on an iterator without a preceding `next()`. Option D is wrong because the loop does not complete and the list is not left containing [B]; the exception interrupts execution before any such state is reached.

34
Multi-Selecteasy

Which TWO statements are true about ArrayList in Java 17? (Choose two.)

Select 2 answers
A.It implements the List interface
B.It implements the Set interface
C.It implements the Queue interface
D.It extends AbstractList
E.It is synchronized
AnswersA, D

ArrayList implements List.

Why this answer

Option A is correct because ArrayList implements the List interface, which is a core part of the Java Collections Framework. This allows ArrayList to be used polymorphically wherever a List is expected, providing ordered, index-based access to elements.

Exam trap

The trap here is that candidates often confuse ArrayList's lack of synchronization with thread safety, or mistakenly think it implements Set or Queue due to its membership in the Collections Framework, but ArrayList is strictly a List implementation.

35
MCQeasy

Given the code snippet: List<String> list = new ArrayList<>(List.of("A","B","C")); list.add("D"); System.out.println(list.size()); What is the result?

A.5
B.UnsupportedOperationException
C.4
D.Compilation fails
E.3
AnswerC

Correct: the new ArrayList is mutable, so add works, size is 4.

Why this answer

Option C is correct because the code creates an ArrayList from a fixed-size list returned by List.of() using the ArrayList constructor, which creates a new mutable list containing the elements "A", "B", "C". The subsequent call to list.add("D") successfully appends the element, resulting in a list of size 4. The ArrayList constructor copies the elements, so the original immutable list is not modified.

Exam trap

The trap here is that candidates mistakenly think the list returned by List.of() is directly used, leading them to expect an UnsupportedOperationException, but the ArrayList constructor creates a separate mutable copy, so the add() succeeds.

How to eliminate wrong answers

Option A is wrong because the list contains only 4 elements after adding "D", not 5. Option B is wrong because UnsupportedOperationException would occur if add() were called directly on the list returned by List.of(), but here the list is wrapped in a new ArrayList, which is fully mutable. Option D is wrong because the code compiles without errors; all types and method calls are valid.

Option E is wrong because the list initially has 3 elements from List.of(), but after adding "D", the size becomes 4, not 3.

36
Multi-Selectmedium

Which two statements are true about the java.util.Comparator and java.lang.Comparable interfaces? (Choose two.)

Select 2 answers
A.Comparator's compare method returns a boolean.
B.Comparator can be used to sort a list in multiple ways.
C.A class implementing Comparable must override equals().
D.Comparable is used to define a natural ordering of objects.
E.Comparator is in java.lang package.
AnswersB, D

True: Multiple Comparators can define different orderings.

Why this answer

Options A and C are correct. Comparable is used to define a natural ordering (A). Comparator can be used to sort a list in multiple ways (C).

Option B is false because Comparator is in java.util. Option D is false because overriding equals is not required. Option E is false because Comparator's compare method returns an int, not boolean.

37
MCQeasy

What is the result of attempting to compile and run the above code?

A.[A, B]
B.[A]
C.[B]
D.Compilation fails
E.Runtime exception
AnswerD

Correct: cannot add non-null to a List<?>.

Why this answer

The code attempts to use `removeIf` on a list created with `Arrays.asList`, which returns a fixed-size list backed by the array. The `removeIf` method modifies the list by removing elements, but the fixed-size list does not support structural modification, resulting in an `UnsupportedOperationException` at runtime. However, the question asks for the result of attempting to compile and run, and since the code compiles without errors, the correct answer is 'D.

Compilation fails'? Wait — the code does compile; the issue is a runtime exception. The correct answer should be 'E. Runtime exception'.

Let me re-evaluate: The code `List<String> list = Arrays.asList("A", "B"); list.removeIf(s -> s.equals("A"));` compiles fine because `removeIf` is a valid method on `List`. At runtime, `Arrays.asList` returns a fixed-size list, and `removeIf` attempts to modify the list structurally, throwing `UnsupportedOperationException`. Therefore, the correct answer is E, not D.

I must correct this: The answer is E. The explanation should reflect that.

Exam trap

The trap here is that candidates often assume `Arrays.asList` returns a regular `ArrayList` and forget that it returns a fixed-size list that does not support structural modification, leading them to expect a successful removal rather than a runtime exception.

How to eliminate wrong answers

Option A is wrong because the list does not become [A, B] after removal; the code throws an exception before any removal. Option B is wrong because the list does not become [A]; the exception prevents any modification. Option C is wrong because the list does not become [B]; the exception occurs before the removal operation completes.

Option D is wrong because the code compiles successfully; `removeIf` is a valid method on `List` and the lambda is syntactically correct.

38
MCQhard

Which is true about CopyOnWriteArrayList?

A.It is not thread-safe.
B.Iterators reflect concurrent modifications.
C.Modifications are expensive as they create a new array.
D.It is optimized for frequent modifications.
AnswerC

Each modification copies the underlying array.

Why this answer

CopyOnWriteArrayList is a thread-safe variant of ArrayList where all mutative operations (add, set, remove, etc.) are implemented by making a fresh copy of the underlying array. This design makes modifications expensive because each modification requires copying the entire array, but it provides safe iteration without locking. Option C correctly identifies that modifications are expensive due to the array copy.

Exam trap

The trap here is that candidates often assume 'thread-safe' collections like CopyOnWriteArrayList allow iterators to see concurrent modifications (like ConcurrentHashMap does), but CopyOnWriteArrayList iterators are snapshot-based and do not reflect modifications after creation.

How to eliminate wrong answers

Option A is wrong because CopyOnWriteArrayList is explicitly thread-safe; it uses a volatile reference and a copy-on-write strategy to ensure visibility and atomicity without external synchronization. Option B is wrong because iterators on CopyOnWriteArrayList reflect a snapshot of the array at the time the iterator was created; they do not see concurrent modifications after creation. Option D is wrong because CopyOnWriteArrayList is optimized for frequent reads and infrequent modifications; modifications are expensive due to array copying, so it is not optimized for frequent modifications.

39
Multi-Selectmedium

Which TWO are valid ways to create an immutable list in Java 17? (Choose two.)

Select 2 answers
A.Arrays.asList("a", "b")
B.List.of(List.of("a", "b"))
C.Collections.unmodifiableList(new ArrayList<>(List.of("a", "b")))
D.List.copyOf(Arrays.asList("a", "b"))
E.new ArrayList<>(List.of("a", "b"))
AnswersC, D

Wraps list to be unmodifiable.

Why this answer

Option C is correct because `Collections.unmodifiableList()` wraps a mutable list in an unmodifiable view, preventing any structural modifications. Option D is correct because `List.copyOf()` creates an immutable list from an existing collection, throwing `NullPointerException` if any element is null. Both produce lists that cannot be modified after creation.

Exam trap

Oracle often tests the distinction between an unmodifiable view (which can be circumvented if the backing list is accessible) and a truly immutable list (which cannot be changed by any means), and candidates mistakenly think `Arrays.asList()` or `new ArrayList<>()` are immutable.

40
MCQhard

A financial application processes transactions in batches. Each transaction is represented as a Transaction object with fields: long id, BigDecimal amount, LocalDateTime timestamp. Transactions are stored in a List<Transaction> in the order they arrive. The system needs to frequently check if a transaction with a specific id exists, and also needs to iterate through transactions in chronological order. The list currently contains millions of transactions, and the existence check is becoming a performance bottleneck because it currently uses a linear search. The system must also maintain insertion order for iteration. Which approach best improves the performance of the existence check while maintaining the required iteration order?

A.Keep List<Transaction> and add a separate HashSet<Long> of ids for fast lookup. Use the list for iteration.
B.Replace List<Transaction> with LinkedHashMap<Long, Transaction> mapping id to transaction. Iterate using values() which preserves insertion order.
C.Keep List<Transaction> and sort it by id. Use Collections.binarySearch() for lookup.
D.Replace List<Transaction> with TreeMap<Long, Transaction> mapping id to transaction. Iterate using values() which returns in natural key order.
AnswerB

LinkedHashMap provides O(1) lookup and maintains insertion order.

Why this answer

Option B is correct because LinkedHashMap maintains insertion order for iteration via its values() view, while providing O(1) key-based lookup for the existence check. This directly addresses the performance bottleneck of linear search in a List without sacrificing the required chronological iteration order.

Exam trap

The trap here is that candidates may confuse TreeMap's natural ordering with insertion order, or assume that sorting a List and using binary search is the best optimization, overlooking the O(1) lookup advantage of hash-based structures like LinkedHashMap.

How to eliminate wrong answers

Option A is wrong because it introduces a separate HashSet<Long> for fast lookup, but this requires manual synchronization to keep the set and list consistent, and the existence check still needs to search the list if the set is not maintained correctly; it adds complexity without a built-in guarantee of order preservation. Option C is wrong because sorting a List by id and using binary search provides O(log n) lookup, which is slower than O(1) hash-based lookup, and sorting by id does not preserve insertion order for iteration unless the list is re-sorted after each addition, which is inefficient. Option D is wrong because TreeMap iterates in natural key order (sorted by id), not insertion order, which violates the requirement to iterate in chronological order.

41
MCQmedium

A developer needs to remove elements from an ArrayList<String> while iterating over it. Which approach is safest and avoids ConcurrentModificationException?

A.for (String s : list) { if (s.equals("x")) list.remove(s); break; }
B.for (int i = 0; i < list.size(); i++) { if (list.get(i).equals("x")) list.remove(i); }
C.Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("x")) it.remove(); }
D.for (String s : list) { if (s.equals("x")) list.remove(s); }
AnswerC

Correctly uses Iterator.remove().

Why this answer

Option C is correct because the Iterator's remove() method is the only safe way to remove elements from a collection while iterating, as it updates both the iterator's internal cursor and the collection's modCount, preventing ConcurrentModificationException. The enhanced for-each loop (options A and D) uses an implicit iterator that does not expose a remove method, so calling list.remove() directly modifies the collection without updating the iterator's state, causing the exception. Option B avoids the exception by using an index-based loop, but it is unsafe because removing an element shifts subsequent elements left, causing the loop to skip the next element and potentially miss removals or throw an IndexOutOfBoundsException.

Exam trap

The trap here is that candidates often assume the index-based loop (option B) is safe because it avoids the exception, but they overlook the logical bug of skipping elements after removal, which the exam tests as a more subtle failure than the obvious ConcurrentModificationException.

How to eliminate wrong answers

Option A is wrong because the enhanced for-each loop uses an implicit iterator; calling list.remove() directly modifies the list without updating the iterator's internal state, causing ConcurrentModificationException on the next iteration (the break prevents the exception only if the removed element is the last one, but the code is still structurally unsound). Option B is wrong because while it avoids ConcurrentModificationException, removing an element by index shifts all later elements left, causing the loop to skip the element that moved into the current index, leading to incorrect removal logic and potential IndexOutOfBoundsException. Option D is wrong because it uses the enhanced for-each loop without a break, so list.remove() triggers ConcurrentModificationException on the next iteration after removal.

42
MCQeasy

Which method of Collection interface returns a primitive int?

A.contains(Object o)
B.isEmpty()
C.toArray()
D.size()
AnswerD

Returns int.

Why this answer

The `size()` method is the only one in the `Collection` interface that returns a primitive `int`, representing the number of elements in the collection. All other methods listed return either a `boolean` or an array of objects, making D the correct answer.

Exam trap

The trap here is that candidates often confuse `isEmpty()` (which returns `boolean`) with `size()` (which returns `int`), or mistakenly think `toArray()` returns a primitive array, but it returns an `Object[]` or a generic array, not a primitive `int[]`.

How to eliminate wrong answers

Option A is wrong because `contains(Object o)` returns a `boolean`, not a primitive `int`. Option B is wrong because `isEmpty()` returns a `boolean`, not a primitive `int`. Option C is wrong because `toArray()` returns an `Object[]` (or a typed array via `toArray(T[])`), not a primitive `int`.

43
MCQhard

Given: TreeSet<Integer> ts = new TreeSet<>(Comparator.reverseOrder()); ts.add(10); ts.add(5); ts.add(20); ts.add(15); System.out.println(ts.first()); What is the result?

A.20
B.15
C.5
D.10
AnswerC

Correct; first() returns the least element in reversed order.

Why this answer

Option C is correct because `TreeSet` with `Comparator.reverseOrder()` sorts elements in descending order (20, 15, 10, 5). The `first()` method returns the smallest element according to the comparator, which in descending order is the last element in the natural order, i.e., 5.

Exam trap

The trap here is that candidates often assume `first()` returns the first element added or the largest element in a reversed set, rather than understanding it always returns the smallest element according to the set's comparator.

How to eliminate wrong answers

Option A is wrong because 20 is the largest element in descending order, but `first()` returns the smallest element according to the comparator, not the largest. Option B is wrong because 15 is not the smallest element in the descending-order sorted set; it is the second largest. Option D is wrong because 10 is not the smallest element; it is the third largest in the descending order.

44
MCQeasy

Which of the following creates an immutable map with two entries?

A.new HashMap<>(Map.of("a",1,"b",2))
B.Map.of("a",1,"b",2)
C.Collections.emptyMap()
D.None of the above
E.new HashMap<>()
AnswerB

Correct: returns an immutable map with two entries.

Why this answer

Option B is correct because `Map.of()` returns an immutable map containing exactly the key-value pairs provided as arguments. This factory method was introduced in Java 9 and creates a fixed-size, unmodifiable map with the two entries "a"→1 and "b"→2.

Exam trap

The trap here is that candidates often confuse creating a mutable copy of an immutable map (option A) with the immutable map itself, or they overlook that `Map.of()` directly produces an immutable map without needing a wrapper.

How to eliminate wrong answers

Option A is wrong because `new HashMap<>(Map.of(...))` creates a mutable HashMap that is a copy of the immutable map, so the result is not immutable. Option C is wrong because `Collections.emptyMap()` returns an immutable empty map, not a map with two entries. Option D is wrong because option B is correct.

Option E is wrong because `new HashMap<>()` creates a mutable empty map, not an immutable map with two entries.

45
MCQhard

Given: Set<Integer> set = new HashSet<>(List.of(1,2,3)); List<Integer> list = new ArrayList<>(set); Collections.sort(list); System.out.println(list); What is the output?

A.[3,2,1]
B.Compilation fails
C.[1,2,3]
D.[1,2]
E.[1,3,2]
AnswerC

Correct: after sorting, the list is in ascending order.

Why this answer

The code creates a HashSet from a List of 1, 2, 3, then copies it into an ArrayList. HashSet does not guarantee order, but Collections.sort() sorts the list in natural ascending order (1, 2, 3). The output is [1,2,3], making option C correct.

Exam trap

The trap here is that candidates assume HashSet preserves insertion order (like LinkedHashSet) and thus expect unsorted output, forgetting that Collections.sort() explicitly sorts the list into ascending order.

How to eliminate wrong answers

Option A is wrong because it shows descending order [3,2,1], which would require Collections.reverseOrder() or a custom comparator, not the default sort. Option B is wrong because the code compiles successfully: all imports are implicitly available (java.util.*) and the methods used are valid. Option D is wrong because it omits the element 3, but HashSet and ArrayList contain all three elements (1,2,3) and sorting does not remove any.

Option E is wrong because [1,3,2] is not sorted; Collections.sort() always produces ascending order for Integers, so 2 must come before 3.

46
MCQhard

Given: Map<String, Integer> map = new HashMap<>(); map.put("x", 10); map.put("y", 20); map.computeIfAbsent("x", k -> 30); map.computeIfPresent("z", (k,v) -> 40); System.out.println(map); What is the output?

A.Compilation fails
B.{x=30, y=20}
C.{x=30, y=20, z=40}
D.{x=10, y=20, z=40}
E.{x=10, y=20}
AnswerE

Correct: both conditions are false, so map unchanged.

Why this answer

Option E is correct because `computeIfAbsent` only inserts a mapping if the key is absent, and since "x" already exists with value 10, the lambda is not executed and the value remains 10. `computeIfPresent` only modifies a mapping if the key is present, and since "z" is not in the map, the lambda is not executed and no entry is added. Thus the map remains {x=10, y=20}.

Exam trap

The trap here is that candidates often confuse `computeIfAbsent` with `put` or `merge`, assuming it always updates the value, and similarly assume `computeIfPresent` will insert a new key-value pair, when in fact both methods only act conditionally based on key presence.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; both `computeIfAbsent` and `computeIfPresent` are valid Map methods. Option B is wrong because it incorrectly assumes `computeIfAbsent` overwrites the existing value for key "x", but it only computes if the key is absent. Option C is wrong because it assumes both methods add or modify entries, but `computeIfPresent` does nothing for a missing key "z".

Option D is wrong because it assumes `computeIfAbsent` does nothing (correct) but also assumes `computeIfPresent` adds an entry for "z", which it does not.

47
MCQhard

Given: Map<Integer, String> map = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); map.entrySet().stream().filter(e -> e.getKey() > 1).forEach(System.out::print); What is output?

A.2=two1=one
B.1=one2=two
C.No output
D.2=two
AnswerD

Only the entry with key 2 passes the filter.

Why this answer

The filter(e -> e.getKey() > 1) retains only the entry with key 2, which is "2=two". The forEach(System.out::print) prints that entry without a newline, so the output is "2=two". Option D is correct.

Exam trap

The trap here is that candidates may forget the filter condition excludes key 1, or mistakenly think the stream prints all entries, leading them to choose options that include both entries or no output.

How to eliminate wrong answers

Option A is wrong because it includes "1=one" which was filtered out (key 1 is not > 1). Option B is wrong because it prints both entries in insertion order, ignoring the filter condition. Option C is wrong because the stream does produce output (the filtered entry is printed).

48
MCQmedium

A TreeSet<String> is used to store a list of employee names. The set currently contains "Alice", "Bob", "Charlie". What is the output after calling set.add("Bob")?

A.Exception
B.false
C.The set becomes ["Alice","Bob","Bob","Charlie"]
D.true
AnswerB

TreeSet implements Set, which does not allow duplicates; add returns false.

Why this answer

Option B is correct because a TreeSet implements the Set interface, which does not allow duplicate elements. When calling add("Bob") on a TreeSet that already contains "Bob", the add method returns false, indicating that the element was not added, and the set remains unchanged.

Exam trap

The trap here is that candidates may confuse the return value of add() with the behavior of a List, expecting an exception or a successful insertion, but the Set interface mandates that duplicates are silently rejected by returning false.

How to eliminate wrong answers

Option A is wrong because TreeSet.add() does not throw an exception when adding a duplicate; it simply returns false. Option C is wrong because a Set, by definition, cannot contain duplicate elements, so the set will not have two "Bob" entries. Option D is wrong because the add method returns false, not true, when the element already exists in the set.

49
MCQeasy

What will be the result of the following code? Object[] arr = new Integer[5]; arr[0] = "String";

A.Successfully stores "String"
B.ArrayStoreException at runtime
C.Compilation error
D.ClassCastException
AnswerB

Runtime type is Integer[], incompatible.

Why this answer

The code creates an array of type `Integer[]` referenced by an `Object[]` variable. At runtime, the array's actual component type is `Integer`, so attempting to store a `String` violates the array's type constraint and throws an `ArrayStoreException`.

Exam trap

The trap here is that candidates see the reference type `Object[]` and assume the array can hold any `Object`, forgetting that the actual runtime type of the array object determines what can be stored, leading them to pick Option A or D.

How to eliminate wrong answers

Option A is wrong because storing a `String` into an `Integer[]` array is not allowed; the JVM performs a runtime type check on the stored element. Option C is wrong because the code compiles successfully: the reference type `Object[]` allows the assignment, and the assignment `arr[0] = "String"` is syntactically valid since `String` is an `Object`. Option D is wrong because `ClassCastException` occurs when an object is cast to an incompatible type, not when an element is stored into an array; the array store check throws `ArrayStoreException` instead.

50
MCQmedium

What does the Map.merge() method do if the specified key is absent?

A.Calls the remapping function with null and the value
B.Associates the key with the given value
C.Throws NullPointerException
D.Removes the key if present
AnswerB

If absent, put value.

Why this answer

When the specified key is absent in the map, the `Map.merge()` method associates the key with the given value without invoking the remapping function. This is specified in the Java API documentation: if the key is not present (or maps to null), the key is associated with the given non-null value.

Exam trap

Oracle often tests the misconception that the remapping function is always called, leading candidates to incorrectly choose option A, when in fact the function is only invoked for existing keys.

How to eliminate wrong answers

Option A is wrong because the remapping function is only called when the key is already present (and maps to a non-null value); when the key is absent, the function is not invoked at all. Option C is wrong because `Map.merge()` does not throw a `NullPointerException` when the key is absent; it only throws `NullPointerException` if the key or value is null (and the map does not support null keys/values), but absence of a key is a normal condition. Option D is wrong because `merge()` never removes a key when it is absent; removal only occurs if the remapping function returns null when the key is present.

51
MCQhard

What is the result of executing this code?

A.Compilation error
B.[b]
C.Runtime exception
D.[b, d]
AnswerC

Collectors.toUnmodifiableList returns an immutable list, calling add throws UnsupportedOperationException.

Why this answer

Option C is correct. Collectors.toUnmodifiableList returns an immutable list, so calling add throws UnsupportedOperationException at runtime. Option A is wrong because the code compiles.

Options B and D are wrong because the add operation fails.

52
MCQeasy

Which of the following correctly converts an array of strings to a List?

A.Collections.toList(array) converts the array.
B.List.of(array) returns a mutable list.
C.Arrays.asList(array) returns a fixed-size list backed by the array.
D.Arrays.asList(array) returns a new ArrayList with a copy of the elements.
AnswerC

Arrays.asList returns a list view of the array, fixed-size and mutable via set operations.

Why this answer

Option C is correct because `Arrays.asList(array)` returns a fixed-size list backed by the original array, meaning changes to the list (like `set`) reflect in the array, but structural modifications (like `add` or `remove`) throw `UnsupportedOperationException`. This is the standard, exam-relevant way to convert an array to a List in Java.

Exam trap

The trap here is that candidates confuse `Arrays.asList()` with creating a fully mutable `ArrayList`, or they think `List.of()` returns a mutable list, but the exam specifically tests the fixed-size, array-backed nature of `Arrays.asList()` versus the immutability of `List.of()`.

How to eliminate wrong answers

Option A is wrong because `Collections.toList(array)` does not exist in the Java Collections Framework; the correct method is `Arrays.asList()`. Option B is wrong because `List.of(array)` returns an immutable list (not mutable), and any attempt to modify it throws `UnsupportedOperationException`. Option D is wrong because `Arrays.asList(array)` does not create a new `ArrayList` with a copy; it returns a fixed-size list backed directly by the original array, so changes to the list affect the array and vice versa.

53
MCQmedium

A developer needs to filter a list of transactions where the amount is greater than 100 and collect the results into a new list. Which approach is best practice for readability and performance?

A.transactions.stream().filter(t -> t.getAmount() > 100).collect(Collectors.toList())
B.List<Transaction> result = new ArrayList<>(); for(Transaction t : transactions) { if(t.getAmount() > 100) result.add(t); }
C.transactions.stream().filter(t -> t.getAmount() > 100).toArray()
D.transactions.removeIf(t -> t.getAmount() <= 100)
AnswerA

Stream API is best practice for filtering and collecting into a new list.

Why this answer

Option A is correct because it uses the Stream API's `filter` method to declaratively select transactions with an amount greater than 100, and `collect(Collectors.toList())` to gather results into a new list. This approach is both readable and performant, leveraging lazy evaluation and internal iteration for efficient processing.

Exam trap

The trap here is that candidates may choose Option D, thinking `removeIf` is a filter, but it mutates the original collection and does not create a new list, which is explicitly required by the question.

How to eliminate wrong answers

Option B is wrong because it uses imperative external iteration with a for-each loop and manual list addition, which is more verbose, less readable, and can be slower due to lack of optimization like parallel stream support. Option C is wrong because `toArray()` returns an array, not a List, failing the requirement to collect into a new list. Option D is wrong because `removeIf` modifies the original list in-place, which violates the requirement to collect results into a new list and may cause side effects or ConcurrentModificationException if the list is unmodifiable.

54
MCQmedium

What is the output of the above code?

A.[a, b]
B.[a, c]
C.[a, b, c]
D.[b, c]
E.Compilation fails
AnswerB

Correct: "b" is removed, leaving a and c.

Why this answer

The code uses `List.remove(Object)` which removes the first occurrence of the specified element. After removing "b" from the list [a, b, c], the list becomes [a, c]. Option B is correct because the output is [a, c].

Exam trap

The trap here is that candidates may confuse `remove(Object)` with `remove(int index)` and think the code removes the element at index 1 (which would be "b" as well), but the correct understanding is that `remove(Object)` removes by value, not by index.

How to eliminate wrong answers

Option A is wrong because it suggests the list remains [a, b], but the removal of "b" changes the list. Option C is wrong because it implies no removal occurred, but the remove operation successfully removes "b". Option D is wrong because it suggests both "a" and "b" are removed, but only "b" is removed.

Option E is wrong because the code compiles and runs without error; `List.remove(Object)` is a valid method.

55
MCQmedium

A method returns a List<Integer>. The caller wants to ensure the list cannot be modified. Which is the best approach?

A.return Arrays.asList(list.toArray());
B.return new ArrayList<>(list);
C.return (List<Integer>) list.clone();
D.return Collections.unmodifiableList(list);
AnswerD

Returns an unmodifiable view.

Why this answer

Option D is correct because `Collections.unmodifiableList()` returns a read-only view of the specified list. Any attempt to modify the returned list (e.g., via `add`, `remove`, `set`) will throw an `UnsupportedOperationException`. This is the standard, recommended approach in the Java Collections Framework to provide an unmodifiable wrapper without copying the underlying data.

Exam trap

The trap here is that candidates often confuse 'unmodifiable view' with 'immutable copy' and may pick options like `Arrays.asList()` or `clone()` thinking they prevent modification, but those still allow structural changes or mutation through the backing array.

How to eliminate wrong answers

Option A is wrong because `Arrays.asList(list.toArray())` creates a fixed-size list backed by the array, but the list itself is still modifiable via `set` and the underlying array can be mutated; it does not guarantee immutability. Option B is wrong because `new ArrayList<>(list)` creates a new mutable copy of the list, allowing the caller to modify it freely. Option C is wrong because `list.clone()` returns a shallow copy of the list, but the returned list is still mutable; additionally, the cast to `List<Integer>` is redundant and the clone method's contract does not guarantee immutability.

56
Multi-Selecthard

Which THREE statements are true about HashSet in Java 17? (Choose three.)

Select 3 answers
A.Does not maintain insertion order
B.Allows duplicate elements
C.Is thread-safe
D.Has constant-time performance for basic operations
E.Allows at most one null element
AnswersA, D, E

Order is not guaranteed.

Why this answer

Option A is correct because HashSet is backed by a HashMap, which uses hash codes to store elements in buckets. The iteration order depends on the hash values and bucket distribution, which can change when the set is resized, so insertion order is not preserved.

Exam trap

The trap here is that candidates often confuse HashSet's lack of ordering with the ability to hold duplicates, or assume that 'constant-time performance' means guaranteed O(1) regardless of hash collisions, but the exam expects you to know that it is amortized constant-time under typical conditions.

57
Multi-Selecteasy

Which TWO statements about HashMap are true? (Select two.)

Select 2 answers
A.It allows null values.
B.It uses red-black trees for collision resolution.
C.It guarantees insertion order.
D.It allows null keys.
E.It is thread-safe.
AnswersA, D

HashMap allows null values for any key.

Why this answer

Option A is correct because HashMap allows null values; you can store null as a value for any key, including null keys. This is explicitly permitted by the HashMap specification, which does not restrict value types.

Exam trap

The trap here is that candidates often confuse HashMap with TreeMap (which does not allow null keys) or with ConcurrentHashMap (which does not allow null keys or values), and may incorrectly assume HashMap is thread-safe because it is widely used in single-threaded contexts.

58
MCQhard

A company's Java 17 application processes large log files and stores word counts. Initially, they used a TreeMap<String, Integer> to maintain sorted word counts. After adding 10 million entries, insertion performance became unacceptably slow. The team switched to a HashMap<String, Integer> for fast insertions, but now they need to produce sorted reports. They are considering two approaches: (1) Keep the HashMap and, when a sorted report is needed, extract all entries into an ArrayList<Map.Entry<String, Integer>> and sort it using Collections.sort with a comparator, or (2) Use a ConcurrentSkipListMap instead. The application is single-threaded, and reports are requested infrequently. What is the best course of action?

A.Use ConcurrentSkipListMap
B.Use LinkedHashMap and convert to sorted list when needed
C.Use HashMap and sort with Collections.sort when needed
D.Revert to TreeMap because it always keeps data sorted
AnswerC

Optimal balance: fast inserts, sorting only on demand.

Why this answer

Option C is correct because the application is single-threaded and reports are infrequent, so the overhead of sorting a HashMap's entries only when needed is acceptable and avoids the continuous insertion cost of a TreeMap. HashMap provides O(1) insertions, and sorting an ArrayList of 10 million entries with Collections.sort (which uses TimSort, O(n log n)) is efficient for occasional use, making this the best balance of performance and simplicity.

Exam trap

The trap here is that candidates assume sorted data must always be maintained in a sorted structure, overlooking the performance trade-off between continuous sorting overhead (TreeMap) and on-demand sorting (HashMap) when insertions are frequent and reads are rare.

How to eliminate wrong answers

Option A is wrong because ConcurrentSkipListMap is designed for concurrent access and provides sorted order, but it has higher overhead per insertion (O(log n)) than HashMap, and the application is single-threaded, so its thread-safety features are unnecessary and degrade performance. Option B is wrong because LinkedHashMap maintains insertion order, not sorted order, so converting it to a sorted list still requires a full sort, offering no advantage over HashMap and adding extra memory overhead for the linked list. Option D is wrong because reverting to TreeMap would reintroduce the original performance problem: TreeMap maintains sorted order at all times with O(log n) insertions, which caused unacceptable slowness with 10 million entries, and the requirement is for fast insertions with only occasional sorted reports.

59
MCQmedium

Consider: List<Integer> list = new LinkedList<>(); list.add(10); list.add(20); list.add(0,5); System.out.println(list); What is the output?

A.[10,5,20]
B.[5,10,20]
C.[10,20,5]
D.[5,10,20] but with type warning
AnswerB

add(0,5) inserts at the beginning.

Why this answer

The code creates a LinkedList and adds 10, then 20. The third call `list.add(0,5)` inserts 5 at index 0, shifting existing elements to the right. The resulting list is [5,10,20], so option B is correct.

Exam trap

The trap here is that candidates often confuse the `add(index, element)` method with `set(index, element)`, or incorrectly assume that adding at index 0 replaces the first element rather than inserting before it.

How to eliminate wrong answers

Option A is wrong because it suggests the list is [10,5,20], which would result from adding 5 at index 1, not index 0. Option C is wrong because [10,20,5] would result from adding 5 at the end (no index specified) or at index 2, not index 0. Option D is wrong because there is no type warning; the code compiles cleanly with generics, and the output is exactly [5,10,20] without any warning.

60
MCQhard

A HashMap uses a mutable object as a key. After adding the key-value pair, the key's fields are changed such that its hashCode changes. Which statement is true?

A.The value can still be retrieved using the modified key
B.The value may not be retrievable using the modified key
C.The entry is automatically moved to the correct bucket
D.An IllegalArgumentException is thrown when modifying the key
AnswerB

Changed hash leads to lookup in wrong bucket.

Why this answer

When a HashMap uses a mutable object as a key and the key's hashCode changes after insertion, the key is stored in the bucket corresponding to its original hash code. The modified key's new hash code will likely map to a different bucket during retrieval, so the value may not be found. Option B is correct because the value may not be retrievable using the modified key, depending on whether the new hash code leads to the same bucket and whether equals() still matches.

Exam trap

The trap here is that candidates assume HashMap automatically handles key mutations or that Java enforces key immutability, but in reality, the contract requires keys to be immutable for correct behavior, and no runtime check is performed.

How to eliminate wrong answers

Option A is wrong because changing the key's hashCode after insertion does not guarantee retrieval; the modified key's new hash code will likely map to a different bucket, so the value may not be found. Option C is wrong because the HashMap does not automatically rehash or move entries when a key's fields change; it only rehashes when the map is resized or when explicitly triggered. Option D is wrong because modifying a mutable key's fields does not throw an IllegalArgumentException; the Java runtime does not enforce immutability of keys at the language level.

61
MCQmedium

A developer is writing a method that takes a Collection<Integer> and returns a List<Integer> containing the same elements in sorted order. The method should not modify the original collection. The developer tries the following code: public List<Integer> sortCollection(Collection<Integer> col) { return col.stream().sorted().collect(Collectors.toList()); } The code compiles and runs, but the team lead says it is not optimal. What improvement should be made?

A.Use parallelStream() for better performance
B.Use a TreeSet and then convert to List
C.Convert the collection to an ArrayList first, then call Collections.sort() on it
D.Return an unmodifiable list using collect(Collectors.toUnmodifiableList())
AnswerD

Ensures result cannot be modified, good practice for API design.

Why this answer

Option D is correct because the current code creates a mutable list via `Collectors.toList()`, but the method contract does not require mutability. Using `Collectors.toUnmodifiableList()` returns an unmodifiable list, which is more memory-efficient and thread-safe, and it aligns with the principle of returning immutable collections when modification is not needed. This improvement does not affect sorting correctness but optimizes the result for immutability.

Exam trap

The trap here is that candidates often focus on performance improvements like parallelism or sorting efficiency, but the actual optimization is about immutability and API design, which is a common subtlety in Java collections questions.

How to eliminate wrong answers

Option A is wrong because `parallelStream()` would introduce overhead for small collections and does not guarantee sorted order without additional synchronization; the current sequential stream is already optimal for sorting. Option B is wrong because using a `TreeSet` would remove duplicate elements (since `TreeSet` is a `Set`), which violates the requirement to preserve all elements from the original collection. Option C is wrong because converting to an `ArrayList` and calling `Collections.sort()` would modify the original collection if the input is already an `ArrayList` (since `Collections.sort()` sorts in place), and it also requires an extra copy step, making it less efficient than the stream-based approach.

62
Multi-Selecteasy

Which TWO of the following will sort a List<String> in natural (ascending) order?

Select 2 answers
A.list.sort(Comparator.naturalOrder());
B.list.sort((a,b) -> b.compareTo(a));
C.Collections.sort(list, Collections.reverseOrder());
D.Collections.sort(list);
E.Arrays.sort(list);
AnswersA, D

Correct: naturalOrder comparator sorts in ascending order.

Why this answer

Option A is correct because `Comparator.naturalOrder()` returns a comparator that imposes the natural (ascending) ordering on `String` objects, which is lexicographic order based on Unicode values. The `List.sort()` method accepts this comparator and sorts the list in place, making it a concise and idiomatic way to sort a list in ascending order.

Exam trap

The trap here is that candidates often confuse `Collections.sort(list)` (which sorts in natural order) with `Collections.sort(list, Collections.reverseOrder())` (which sorts in reverse order), and may also mistakenly think `Arrays.sort()` works on a `List` without realizing it requires an array.

63
MCQmedium

Given: TreeSet<Integer> set = new TreeSet<>(List.of(3,1,2)); set.add(2); System.out.println(set); What is the output?

A.[1,2]
B.[1,3,2]
C.[3,1,2]
D.UnsupportedOperationException
E.[1,2,3]
AnswerE

Correct: sorted order, duplicates ignored.

Why this answer

E is correct because TreeSet maintains elements in their natural sorted order (ascending for integers). The list [3,1,2] is sorted to [1,2,3], and adding 2 again has no effect since TreeSet does not allow duplicates. The output is [1,2,3].

Exam trap

The trap here is that candidates often confuse TreeSet with HashSet or List, expecting insertion order or allowing duplicates, but TreeSet enforces sorted order and uniqueness via its underlying tree structure.

How to eliminate wrong answers

Option A is wrong because it omits the element 3, but TreeSet retains all unique elements after sorting. Option B is wrong because it shows [1,3,2], which is not sorted order; TreeSet always sorts elements. Option C is wrong because it shows the original insertion order [3,1,2], but TreeSet does not preserve insertion order.

Option D is wrong because UnsupportedOperationException is not thrown; TreeSet supports add() and duplicates are silently ignored.

64
MCQmedium

A developer needs to sort a List of Employee objects by salary (double) in descending order. Which approach is correct and efficient?

A.Collections.sort(list, Collections.reverseOrder());
B.list.stream().sorted((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary())).collect(Collectors.toList());
C.Collections.sort(list, (e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary()));
D.Collections.sort(list);
AnswerC

Uses Comparator with descending order via Double.compare.

Why this answer

Option C is correct because it uses `Collections.sort()` with a custom `Comparator` that performs an in-place sort of the original list, which is both efficient (no new list created) and correctly orders by salary descending via `Double.compare(e2.getSalary(), e1.getSalary())`. This avoids the overhead of stream pipeline creation and collection, and directly mutates the list as required.

Exam trap

The trap here is that candidates often choose the stream-based approach (Option B) thinking it is more modern or functional, but the exam tests understanding that `Collections.sort()` with a custom comparator is the correct and efficient way to sort a mutable list in-place, while streams create a new collection and are less efficient for this specific requirement.

How to eliminate wrong answers

Option A is wrong because `Collections.reverseOrder()` reverses the natural ordering of `Employee` objects, but `Employee` does not implement `Comparable` (or its natural ordering is not by salary), so this will cause a compilation error or use an unintended ordering. Option B is wrong because it creates a new sorted list via a stream and `collect(Collectors.toList())`, which is less efficient than an in-place sort and does not modify the original list as the question implies. Option D is wrong because `Collections.sort(list)` uses the natural ordering of `Employee` (via `Comparable`), which is not defined for salary descending, and will likely result in a compile-time error if `Employee` does not implement `Comparable`.

65
MCQeasy

Given: String[] array = {"A", "B"}; List<String> list = Arrays.asList(array); list.set(0, "C"); array[1] = "D"; What is the content of the list?

A.[A, D]
B.[C, D]
C.[A, B]
D.[C, B]
AnswerB

Both modifications affect the list.

Why this answer

Option B is correct because `Arrays.asList()` returns a fixed-size list backed by the original array. Modifications to the list via `set()` directly affect the backing array, and modifications to the array elements are reflected in the list. After `list.set(0, "C")`, the first element of both the list and the array becomes "C".

After `array[1] = "D"`, the second element of both becomes "D". Thus the list content is [C, D].

Exam trap

The trap here is that candidates often forget that `Arrays.asList()` returns a list backed by the original array, so modifications through either reference are reflected in both, leading them to choose options that reflect only one of the two changes.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes only the array modification affects the list, ignoring the `list.set(0, "C")` operation. Option C is wrong because it assumes the list remains unchanged, failing to recognize that both `set()` and direct array assignment modify the shared backing structure. Option D is wrong because it reflects only the `set()` operation but ignores the effect of `array[1] = "D"`, which also updates the list.

66
MCQhard

Given the above Java version, which of the following is NOT a standard Java 17 feature?

A.All of the above are standard
B.Sealed classes
C.Text blocks
D.Pattern matching for switch (preview)
E.Records
AnswerD

Correct: This is a preview feature in Java 17, not standard.

Why this answer

Option D is correct because pattern matching for switch is a preview feature in Java 17, not a standard feature. It was introduced as a preview under JEP 406 and requires the --enable-preview flag to be used. Standard features in Java 17 are finalized and do not require any preview flags.

Exam trap

The trap here is that candidates may assume pattern matching for switch is a standard feature because it is widely discussed and similar to other finalized features like records or sealed classes, but Oracle deliberately kept it in preview in Java 17 to test further refinements.

How to eliminate wrong answers

Option A is wrong because it claims all options are standard, but D is a preview feature, so A is false. Option B is wrong because sealed classes are a standard feature in Java 17 (JEP 409), finalized and available without flags. Option C is wrong because text blocks are a standard feature since Java 15 (JEP 378), fully supported in Java 17.

Option E is wrong because records are a standard feature since Java 16 (JEP 395), finalized and included in Java 17.

67
Multi-Selecthard

Which THREE of the following variable declarations are valid in Java 17?

Select 3 answers
A.List<?> list = new ArrayList<String>();
B.List<Object> list = new ArrayList<String>();
C.List<? super Integer> list = new ArrayList<Number>();
D.List<? extends Number> list = new ArrayList<Integer>();
E.List<?> list = new ArrayList<?>();
AnswersA, C, D

Correct: wildcard captures any type.

Why this answer

Option A is correct because `List<?>` is a wildcard type that can hold any type, and `new ArrayList<String>()` creates an `ArrayList` of a specific type (`String`). The wildcard `?` acts as a type-safe placeholder, allowing the assignment of a concrete parameterized type to an unbounded wildcard reference. This is valid because the wildcard represents an unknown type, and the list is read-only in terms of type safety (you cannot add elements except `null`).

Exam trap

The trap here is that candidates often confuse generic invariance with array covariance, mistakenly thinking `List<Object>` can hold a `List<String>` (like `Object[]` can hold `String[]`), or they incorrectly assume wildcards can be used in instantiation expressions like `new ArrayList<?>()`.

68
MCQhard

Given: Map<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.merge("A", 3, (v1, v2) -> v1 + v2); System.out.println(map.get("A")); What is the result?

A.1
B.4
C.3
D.null
AnswerB

Correct: 1+3=4.

Why this answer

The correct answer is B (4) because the `merge` method on a Map associates the key "A" with the result of applying the remapping function `(v1, v2) -> v1 + v2` to the current value (1) and the given value (3), producing 1 + 3 = 4. If the key had been absent, the new value would be 3, but since it is present, the function is invoked and the result replaces the old value.

Exam trap

The trap here is that candidates often confuse `merge` with `put` or `replace`, forgetting that the remapping function combines the old and new values rather than simply overwriting with the new value.

How to eliminate wrong answers

Option A is wrong because it assumes the merge operation is ignored or that the original value 1 remains unchanged, but merge always applies the remapping function when the key is present. Option C is wrong because it mistakenly treats the merge as a simple put that overwrites with the new value 3, ignoring the remapping function. Option D is wrong because it suggests the key "A" becomes null, but merge never removes a mapping unless the remapping function returns null, which it does not here.

69
MCQmedium

Which Map implementation guarantees that keys are sorted in their natural order?

A.TreeMap
B.Hashtable
C.LinkedHashMap
D.HashMap
AnswerA

TreeMap implements NavigableMap, which sorts keys by their natural order or a provided Comparator.

Why this answer

TreeMap implements the SortedMap interface, which ensures that keys are stored in their natural ordering (as defined by Comparable) or by a provided Comparator. This makes TreeMap the only standard Map implementation that guarantees sorted keys without external sorting.

Exam trap

The trap here is that candidates often confuse insertion order (LinkedHashMap) with sorted order (TreeMap), or assume HashMap maintains some predictable order, when in fact only TreeMap guarantees sorted keys.

How to eliminate wrong answers

Option B (Hashtable) is wrong because it is a legacy synchronized Map that does not maintain any order of keys. Option C (LinkedHashMap) is wrong because it maintains insertion order (or access order), not sorted order. Option D (HashMap) is wrong because it offers O(1) performance but makes no guarantees about key ordering and can even change order after resizing.

70
MCQmedium

What is the output of the program?

A.[A, B, C, D]
B.[A, B, D]
C.[A, B, C]
D.[B, C, D]
AnswerC

Correct: D removed.

Why this answer

The code uses `List.remove(Object)` which removes the first occurrence of the specified element. After removing 'C', the list becomes [A, B, D]. Then `List.remove(int index)` is called with index 2, which removes the element at that index (now 'D'), resulting in [A, B].

However, the question's correct answer is [A, B, C] because the code actually prints the list after the first removal only, not after both. The second removal is not printed. Option C is correct because the output is the list after removing 'C' only.

Exam trap

The trap here is that candidates often assume both removal operations are printed, or they confuse the overloaded `remove(Object)` with `remove(int index)`, leading them to misidentify which elements are removed and when the output is captured.

How to eliminate wrong answers

Option A is wrong because it assumes no removal occurs, but 'C' is successfully removed via `remove(Object)`. Option B is wrong because it shows the result after both removals, but the code only prints the list after the first removal. Option D is wrong because it suggests 'A' is removed, but 'A' is never removed; the first removal targets 'C' and the second targets index 2 (which is 'D' after the first removal).

71
MCQhard

A developer writes: ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); Object[] arr = list.toArray(); arr[0] = "one"; What happens?

A.Compiles and runs, but arr[0] becomes "one"
B.Cannot cast String to Integer at runtime
C.Compilation error because toArray returns Integer[]
D.Runtime error
AnswerA

The array is Object[], so assigning a String is fine.

Why this answer

The `ArrayList.toArray()` method returns an `Object[]` array, not an `Integer[]`. Since the reference variable `arr` is declared as `Object[]`, the assignment is valid. Assigning a `String` to `arr[0]` is allowed because `Object[]` can hold any object type.

No compilation or runtime error occurs because the array's runtime type is `Object[]`, and the assignment is type-safe at compile time and runtime.

Exam trap

The trap here is that candidates mistakenly think `toArray()` returns a typed array (e.g., `Integer[]`) because of the generic declaration, but without an argument it always returns `Object[]`, making the subsequent assignment to a String perfectly valid.

How to eliminate wrong answers

Option B is wrong because there is no cast from String to Integer at runtime; the array is `Object[]`, so storing a String is perfectly legal. Option C is wrong because `toArray()` without arguments always returns `Object[]`, not `Integer[]`; the generic type parameter is erased at runtime. Option D is wrong because no runtime error occurs; the code compiles and runs successfully, and the array element is simply reassigned to a String.

72
MCQmedium

A financial application processes transactions as List<Transaction> objects. The application runs on a server with limited memory (2 GB heap). The development team observes that after processing a large number of transactions (over 10 million), heap usage spikes to near 1.8 GB and garbage collection pauses become frequent (over 5 seconds). The Transaction class is defined as public record Transaction(LocalDateTime timestamp, double amount, String category) {}. The current processing code reads all transactions from a database result set into an ArrayList<Transaction> using a loop with list.add(). Then the list is sorted by timestamp using Collections.sort(list, Comparator.comparing(Transaction::timestamp)). The sorted list is then iterated multiple times to generate various reports. The code runs in a single-threaded context. Which change would most effectively reduce peak memory usage while preserving the sorted report output?

A.Use a TreeMap<LocalDateTime, List<Transaction>> to group by timestamp, then flatten on iteration.
B.Use a SortedSet<Transaction> (java.util.TreeSet) with a comparator to store transactions in sorted order.
C.Use a parallel stream with .sorted() and collect to a ConcurrentLinkedDeque.
D.Collect transactions into an array (Transaction[]) and sort using Arrays.sort().
AnswerD

An array avoids the overhead of ArrayList's internal array expansion (which may overallocate up to 50%) and uses contiguous memory with no wrapper objects, reducing memory footprint.

Why this answer

Option C is correct because using an array (Transaction[]) avoids the overhead of ArrayList's internal array expansion (which may overallocate up to 50% additional capacity) and uses contiguous memory with no wrapper objects, reducing memory footprint. Option A increases memory due to Map and List overhead. Option B loses duplicate transactions.

Option D adds overhead from parallel streams and concurrent collections.

Page 1 of 2 · 86 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Arrays Collections questions.