Java OCA OCP Practice Question 2334

Question

Which declarations can be inserted at (1) so that the program compiles and runs without errors?

public class Main {
  public static void main(String[] args) {
    // (1) INSERT DECLARATION HERE
    appendAndPrint(lst, "hello");
  }/*from  w  w  w  .  j  a  va2 s.c  o m*/

  static <T> void appendAndPrint(Collection<T> ds, T t) {
    ds.add(t);
    System.out.println(ds);
  }
}

Select the two correct answers.

  • (a) List<?> lst = new LinkedList<Object>();
  • (b) List<? extends Object> lst = new LinkedList<Object>();
  • (c) List<? super Object> lst = new LinkedList<Object>();
  • (d) List<Object> lst = new LinkedList<Object>();


(c) and (d)

Note

(a) The method appendAndWrite(Collection<T>,T) cannot be applied to the inferred argument type (List<capture-of#n ?>, String).

We cannot add to a collection of type Collection<?>.

(b) The method appendAndWrite(Collection<T>,T) cannot be applied to the inferred argument type (List<capture-of#m ? extends Object>, String).

We cannot add to a collection of type Collection<? extends Object>.

(c) The method appendAndWrite(Collection<T>,T) can be applied to the inferred argument type (List<capture-of#k ?superObject>, String).

T is Object.

We can add any object to a collection of type Collection<? super Object>.

(d) The method appendAndWrite(Collection<T>,T) can be applied to the inferred argument type (List<Object>, String).

T is Object.

We can add any object to a collection of type Collection<Object>.




PreviousNext

Related