I am preparing for OCJP. I found a question in dump
import java.util.*;
public class G1 {
public void takeList(List<? extends String> list) {
// insert code here
}
}
Which three code fragments, inserted independently at line 6, will compile? (Choose three.)
A. list.add("foo");
B. Object o = list;
C. String s = list.get(0);
D. list = new ArrayList<String>();
E. list = new ArrayList<Object>();
Answer: B,C,D
I have a query that if List<? extends String that means it matches with String class and all the subclass of String class.
Can anyone justify the answer shown here?
A is incorrect, because your list could be a
List<SomeStringSubClass>, and it would thus be invalid to add a String to it. (I know String is final, but the compiler doesn’t care about it here).E is incorrect because a
List<Object>can’t be assigned to aList<? extends String>, obviously, since the objects contained by aList<Object>don’t necessarily are of type String or of a subclass of String.The other three ones are OK:
List<? extends String>contains instances of String, or instances of a subclass of String. And an instance of a sublcass is also an instance of the superclass.ArrayList<String>is aList<String>, and aList<String>is also aList<? extends String>