Java OCA OCP Practice Question 1581

Question

We want this code to print the titles of each book twice.

Why doesn't it?

LinkedList<String> list = new LinkedList<>();
list.add("MyClass");
list.add("1984");
 
list.forEach(System.out::println);
 
Iterator it = list.iterator();
while (it.hasMore())
  System.out.println(it.next());
  • A. The generic type of Iterator is missing.
  • B. The hasMore() method should be changed to hasNext().
  • C. The iteration code needs to be moved before the forEach() since the stream is used up.
  • D. None of the above. The code does print each book title twice.


B.

Note

The Iterator interface uses the hasNext() and next() methods to iterate.

Since there is not a hasMore() method, it should be changed to hasNext(), making Option B the answer.

With respect to Option A, the missing generic type gives a warning, but the code still runs.

For Option C, iterators can run as many times as you want, as can the forEach() method on list.




PreviousNext

Related