Java OCA OCP Practice Question 3151

Question

Which code, when inserted at (1), will result in the following output:

Before: [Apple, Orange, Apple]
After:  [Orange]

from the program when compiled and run?

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class MyClass {//from  w ww .  ja v  a  2s.c om
   private String fName;

   MyClass(String fName) {
      this.fName = fName;
   }

   public void setName(String newName) {
      this.fName = newName;
   }

   public String toString() {
      return fName;
   }

   public boolean equals(Object other) {
      if (this == other)
         return true;
      if (!(other instanceof MyClass))
         return false;
      return fName.equalsIgnoreCase(((MyClass) other).fName);
   }
}

public class Main {
   public static void main(String[] args) {
      MyClass apple = new MyClass("Apple");
      MyClass orange = new MyClass("Orange");
      List<MyClass> list = new ArrayList<MyClass>();
      list.add(apple);
      list.add(orange);
      list.add(apple);
      System.out.println("Before: " + list);
      // (1) INSERT CODE HERE ...
      System.out.println("After:  " + list);
   }
}

Select the two correct answers.

(a) for (MyClass f : list) {
      if (f.equals(apple))
        list.remove(f);//from  w w w . j a  v a  2 s. co m
    }

(b) int i = 0;
    for (MyClass f : list) {
      if (f.equals(apple))
        list.remove(i);
      i++;
    }

(c) for (int j = 0; j < list.size(); j++) {
      MyClass f = list.get(j);
      if (f.equals(apple))
        list.remove(j);
    }

(d) Iterator<MyClass> itr = list.iterator();
    while (itr.hasNext()) {
      MyClass f = itr.next();
      if (f.equals(apple))
        itr.remove();
    }


(c) and (d)

Note

The for(:) loop does not allow the list to be modified structurally.

In (a) and (b), the code will throw a java.util.ConcurrentModificationException.

Note that the iterator in (d) is less restrictive than the for(:) loop, allowing elements to be removed in a controlled way.




PreviousNext

Related