为什么数组是协变的,但是泛型是不变的?来自约书亚·布洛赫的有效Java,数组与泛型类型有两种重要的区别。首先,数组是协变的。泛型是不变的。协变简单地表示,如果X是Y的子类型,那么X[]也将是Y[]的子类型。数组是协变量的,因为字符串是对象的子类型,所以String[] is subtype of Object[]不变的意思是不管X是不是Y的子类型, List<X> will not be subType of List<Y>.我的问题是,为什么决定在Java中使数组协变?还有其他这样的帖子,比如为什么数组是不变的,但是列表是协变量的呢?,但他们似乎专注于Scala,我无法理解。
3 回答
莫回无
TA贡献1865条经验 获得超7个赞
String[] strings = new String[2];Object[] objects = strings; // valid, String[] is Object[]objects[0] = 12; // error, would cause java.lang.ArrayStoreException: java.lang.Integer during runtime
List<String> strings = new ArrayList<String>();List<Object> objects = strings; // let's say it is validobjects.add(12); // invalid, Integer should not be put into List<String> but there is no information during runtime to catch this
String first = strings.get(0); // would cause ClassCastException, trying to assign 12 to String
慕桂英546537
TA贡献1848条经验 获得超10个赞
泛型不是协变的
Number[]
Integer[]
Number[]
Number[]
Integer[]
List<Number>
List<Integer>
List<Integer>
List<Number>
List<Integer>
List<Number>
List<Integer>
:
List<Integer> li = new ArrayList<Integer>();List<Number> ln = li; // illegalln.add(new Float(3.1415));
List<Number>
li
添加回答
举报
0/150
提交
取消