CCNA Working with Arrays and Collections Questions

10 of 86 questions · Page 2/2 · Working with Arrays and Collections · Answers revealed

76
MCQhard

Given: HashSet<String> set = new HashSet<>(); set.add("A"); set.add("B"); set.add("C"); set.add("A"); System.out.println(set.size()); What is the output?

A.Compilation fails
B.3
C.4
D.2
AnswerB

Correct, only unique elements counted.

Why this answer

Option B is correct because HashSet does not allow duplicate elements. When adding "A" twice, the second add is ignored, so the set contains only three unique elements: "A", "B", and "C". Therefore, set.size() returns 3.

Exam trap

The trap here is that candidates may forget that Set collections (unlike List) inherently reject duplicates, leading them to count all add() calls including the duplicate "A" and choose 4.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; there are no syntax or type errors. Option C is wrong because it assumes duplicates are counted, but HashSet uses equals() and hashCode() to reject duplicates, so size is not 4. Option D is wrong because it incorrectly counts only two elements, missing that "B" and "C" are also present.

77
MCQhard

What is the cause of the ClassCastException?

A.The store map is not type-safe.
B.The value stored is Integer but retrieved as String.
C.The get method should use (T) cast instead of type.cast().
D.The type parameter T is not used correctly.
AnswerB

Correct cause.

Why this answer

The ClassCastException occurs because the code retrieves a value from the store map and attempts to cast it to String, but the actual stored object is an Integer. Since the map is not using generics (raw type), the compiler does not enforce type safety, allowing the mismatch to be caught only at runtime.

Exam trap

The trap here is that candidates may confuse the lack of type safety (Option A) with the direct cause of the exception, which is the actual type mismatch at retrieval time.

How to eliminate wrong answers

Option A is wrong because the store map is not type-safe, but that is not the direct cause of the ClassCastException; the exception is caused by the retrieval mismatch, not the lack of type safety itself. Option C is wrong because using (T) cast instead of type.cast() would not prevent the exception; both approaches would still fail at runtime if the actual object type is incompatible. Option D is wrong because the type parameter T is not used correctly, but the question asks for the cause of the ClassCastException, which is specifically the value being Integer while retrieved as String.

78
Drag & Dropmedium

Arrange the steps to create and use a generic method in Java.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Generic methods allow type-safe operations on different types. The type parameter is placed before the return type.

79
MCQhard

What is the result of executing the code in the exhibit?

A.The code compiles and runs without output.
B.[A, C]
C.ConcurrentModificationException is thrown.
D.[A, B]
AnswerC

Modification during enhanced for loop causes exception.

Why this answer

The code uses an ArrayList and iterates over it with an enhanced for-each loop while simultaneously removing an element via the list's remove() method. This structural modification directly from the list (not via the iterator's remove()) triggers a ConcurrentModificationException because the iterator's modCount check fails. The exception is thrown at the next iteration attempt after the removal.

Exam trap

The trap here is that candidates often think removing an element during iteration is safe if done via the list's remove() method, not realizing that the for-each loop's iterator detects the structural modification and throws ConcurrentModificationException.

How to eliminate wrong answers

Option A is wrong because the code does not compile and run without output; it throws an exception at runtime. Option B is wrong because [A, C] would only appear if the removal succeeded without exception, but the removal of 'B' during iteration causes a ConcurrentModificationException before any output. Option D is wrong because [A, B] would be the result if the removal was done correctly via the iterator's remove() method or if the loop completed without modification, but the code uses list.remove() which is not allowed during iteration.

80
MCQmedium

A team uses a TreeSet with a custom Comparable that returns 0 for objects that are not logically equal (e.g., based on one field but objects differ in another). What is the likely outcome when adding such objects?

A.The second object is not added because TreeSet considers it a duplicate
B.The second object replaces the first
C.A ClassCastException is thrown
D.Both objects are added and insertion order is preserved
AnswerA

TreeSet uses compareTo for equality; returning 0 means duplicate.

Why this answer

TreeSet uses the compareTo() method of the Comparable interface (or Comparator) to determine ordering and equality. When compareTo() returns 0 for two objects that are not logically equal (e.g., they share the same field used in comparison but differ in other fields), TreeSet treats them as duplicates and does not add the second object. This is because TreeSet relies on the comparison result, not the equals() method, for uniqueness.

Exam trap

The trap here is that candidates assume TreeSet uses equals() for duplicate detection, but it actually uses compareTo()/compare(), so objects that are not logically equal can be incorrectly treated as duplicates if the comparison method returns 0.

How to eliminate wrong answers

Option B is wrong because TreeSet never replaces an existing element; it simply refuses to add a duplicate when compareTo() returns 0. Option C is wrong because no ClassCastException occurs unless the objects are not mutually comparable (e.g., different types without a shared Comparable implementation), which is not the case here. Option D is wrong because TreeSet does not preserve insertion order; it maintains elements in sorted order according to the Comparable/Comparator, and duplicates are not added at all.

81
MCQmedium

When should LinkedList be preferred over ArrayList?

A.Frequent random access by index
B.Fast iteration over all elements
C.Minimal memory overhead
D.Frequent insertions and deletions at arbitrary positions
AnswerD

LinkedList has O(1) operations if position known via iterator.

Why this answer

LinkedList is preferred over ArrayList when frequent insertions and deletions occur at arbitrary positions because LinkedList uses a doubly-linked list structure, allowing O(1) time for insertions/deletions once the node is located, whereas ArrayList requires shifting elements (O(n)) due to its underlying array. This makes D correct for scenarios with heavy modification in the middle of the list.

Exam trap

The trap here is that candidates assume LinkedList is always faster for insertions/deletions anywhere, overlooking that random access by index is O(n) and that the overhead of finding the insertion point can make ArrayList more efficient in practice for many use cases.

How to eliminate wrong answers

Option A is wrong because LinkedList provides O(n) random access by index (traversing from head/tail), while ArrayList offers O(1) index-based access via its array backing. Option B is wrong because fast iteration over all elements is equally efficient for both (O(n)), but ArrayList has better cache locality and lower overhead per element, making it generally faster for iteration. Option C is wrong because LinkedList has higher memory overhead due to storing node objects with forward and backward pointers (typically 24+ bytes per element), whereas ArrayList stores elements in a compact contiguous array with minimal overhead.

82
MCQeasy

A developer needs to iterate over an ArrayList of integers and remove all elements that are less than 10. Which approach is best to avoid ConcurrentModificationException?

A.Use a for loop with index and list.remove(index) decrementing index.
B.Use an Iterator with iterator.remove().
C.Use a for-each loop with list.remove().
D.Use list.removeIf() with a lambda expression.
AnswerD

removeIf is the cleanest and safest way; it uses an internal iterator and avoids ConcurrentModificationException.

Why this answer

Option D is correct because `list.removeIf()` is a built-in method introduced in Java 8 that safely removes elements from a collection based on a predicate, handling all iteration and modification internally without throwing ConcurrentModificationException. It uses an internal iterator that properly coordinates structural modifications, making it the most concise and reliable approach for this task.

Exam trap

The trap here is that candidates often choose the Iterator approach (Option B) because they know it avoids ConcurrentModificationException, but they overlook that `removeIf()` is the more modern, concise, and recommended method for such bulk removal operations in Java.

How to eliminate wrong answers

Option A is wrong because using a for loop with index and `list.remove(index)` while decrementing the index can still cause issues if not carefully managed (e.g., shifting elements), and it is error-prone and less efficient than the dedicated removal methods. Option B is wrong because while `Iterator.remove()` is safe and avoids ConcurrentModificationException, it is more verbose and not the 'best' approach compared to `removeIf()`, which is simpler and more expressive. Option C is wrong because using a for-each loop with `list.remove()` directly modifies the list during iteration, which throws ConcurrentModificationException as the for-each loop uses an internal iterator that detects concurrent modification.

83
MCQeasy

A developer is designing a method that returns an immutable list of strings from an array. Which approach best follows current Java best practices?

A.Return new ArrayList<>(Arrays.asList(array))
B.Return Collections.unmodifiableList(Arrays.asList(array))
C.Return Arrays.asList(array)
D.Return List.of(array)
AnswerD

List.of returns an immutable list, introduced in Java 9, and rejects nulls, making it the best practice.

Why this answer

Option A is correct because List.of returns an immutable list, introduced in Java 9, and rejects nulls, making it the best practice. Option B returns a fixed-size list that is mutable via set() and allows nulls, so it is not immutable. Option C works but is verbose and still allows nulls; List.of is preferred.

Option D returns a mutable list.

84
MCQeasy

Which interface provides the ability to store key-value pairs and allows null keys?

A.ConcurrentHashMap
B.TreeMap
C.HashMap
D.Hashtable
AnswerC

Allows null keys.

Why this answer

HashMap is the correct answer because it implements the Map interface, allows null keys (only one null key is permitted), and does not synchronize its operations, making it suitable for unsynchronized key-value storage. In contrast, ConcurrentHashMap, TreeMap, and Hashtable all prohibit null keys for various reasons, such as thread-safety guarantees or sorting requirements.

Exam trap

The trap here is that candidates often confuse HashMap's allowance of null keys with Hashtable's historical prohibition, or assume that all Map implementations support null keys, when in fact only HashMap (and LinkedHashMap) permit null keys among the commonly used implementations.

How to eliminate wrong answers

Option A is wrong because ConcurrentHashMap does not allow null keys or null values, as its design for concurrent access requires non-null keys to avoid ambiguity in synchronization. Option B is wrong because TreeMap does not permit null keys (though it allows null values), as it relies on natural ordering or a Comparator that would throw a NullPointerException when comparing null. Option D is wrong because Hashtable is a legacy synchronized class that does not allow null keys or null values, throwing a NullPointerException if attempted.

85
Multi-Selecteasy

Which THREE are methods of the Map.Entry interface? (Java 17)

Select 3 answers
A.getValue()
B.getHash()
C.getKey()
D.setValue(V value)
E.getValueOrDefault()
AnswersA, C, D

Returns the value.

Why this answer

Option A is correct because the Map.Entry interface in Java defines the getValue() method, which returns the value associated with the entry's key. This method is part of the core contract for accessing key-value pairs within a Map.

Exam trap

The trap here is that candidates confuse methods of the Map interface (like getOrDefault) with methods of the Map.Entry interface, or assume a getHash() method exists due to familiarity with hash-based collections like HashMap.

← PreviousPage 2 of 2 · 86 questions total

Ready to test yourself?

Try a timed practice session using only Working with Arrays and Collections questions.