Java OCA OCP Practice Question 1609

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.stream().forEach(System.out::println);


Iterator it = list.iterator();/*  w  w w . ja va2 s.  c o m*/
while (it.hasNext())
   System.out.println(it.next());
  • A. The generic type of Iterator is missing.
  • B. The hasNext() method should be changed to isNext().
  • 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.


D.

Note

The missing generic type gives a warning, but the code still runs, so Option A is incorrect.

The Iterator interface uses hasNext() and next() methods to iterate, so Option B is incorrect.

Option C applies to calling the same stream twice.

One of our calls is to an Iterator anyway, so Option C is incorrect.

This code is in fact correct, making the answer Option D.




PreviousNext

Related