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选项为什么是错的啊?
:
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选项为什么是错的啊?
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.
(null没有数据类型,可以添加null)
就楼主的题目而言,是这个说法:
比方说你这个?替代的可能是String的子类ChildString(String是否能继承就姑且不说了),那么你当然不能将一个String放到List<ChildString>中,(大家都知道反过来是可以的)。
继承了String的instance才可以放进去