ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
List<Integer> l = new ArrayList<>(List.of(5, 6, 7));
Iterator<Integer> it = l.iterator();
while (it.hasNext()) if (it.next() % 2 == 1) it.remove();
l.add(0, 1);
l.remove(Integer.valueOf(6));
System.out.print(l + " " + l.size());
  1. A. [1] 1
  2. B. [1, 6] 2
  3. C. [6] 1
  4. D. [1, 7] 2

Correct answer: A. [1] 1

Iterator.remove is the safe way to delete while iterating, leaving [6]. add(0, 1) gives [1, 6], and remove(Integer.valueOf(6)) removes the value 6 (not index 6), leaving [1] with size 1.

More OOP with C++ and Java questions

Exams that ask this topic