Given
:
3. import java.util.*;
4. public class G1{
5. public void takeList(List<? extends String> list){
6. //insert code here
7. }
8. }
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>();
答案:BCD
我就不明白,A选项为什么是错的啊?

解决方案 »

  1.   

    找了一段,我自己都没怎么看懂,更不会怎么解释了,今天杯具之极,LZ参考下吧
    There is, as usual, a price to be paid for the flexibility of using wildcards. That price is that it is now illegal to write into shapes in the body of the method. For instance, this is not allowed:    public void addRectangle(List<? extends Shape> shapes) {
            shapes.add(0, new Rectangle()); // Compile-time error!
        }You should be able to figure out why the code above is disallowed. The type of the second parameter to shapes.add() is ? extends Shape-- an unknown subtype of Shape. Since we don't know what type it is, we don't know if it is a supertype of Rectangle; it might or might not be such a supertype, so it isn't safe to pass a Rectangle there.
      

  2.   

    还有 ? supper(exdends) XXX(之类可以是类,也可以是接口)使用extends 这里类必须是XXX的子类(不包括他本身),或者实现他的接口

    (null没有数据类型,可以添加null)
      

  3.   

    1楼找的这一段解释真不错。
    就楼主的题目而言,是这个说法:
    比方说你这个?替代的可能是String的子类ChildString(String是否能继承就姑且不说了),那么你当然不能将一个String放到List<ChildString>中,(大家都知道反过来是可以的)。
      

  4.   

    List<? extends String> list
    继承了String的instance才可以放进去