如下:
import java.util.*;
class Snow{}
class Powder extends Snow{}
class Crusty extends Snow{}
class Slush extends Snow{}
class Light extends Powder{}
class Heavy extends Powder{}
public class AsListInference {
public static void main(String[] args){
List<Snow> snow1=Arrays.asList(new Crusty(),new Slush(),new Powder());
//List<Snow> snow2=Arrays.asList(new Light(),new Heavy());
//这句编译错误,提示不能从List<Powder>转换为List<Snow>
List<Snow> snow3=new ArrayList<Snow>();
Collections.addAll(snow3, new Light(),new Heavy());
List<Snow> snow4=Arrays.<Snow>asList(new Light(),new Heavy());
}
}
snow1和snow2里的对象不都是从snow中继承过来的吗?应该能够向上转型才对啊,但是为什么snow1能创建而snow2不能创建呢?
谁能准确的解释一下Arrays.asList()方法是用的规则?
------解决方案--------------------
强烈不推荐这种写法,
要不用老版jdk的写法Arrays.asList(new Snow[]{new Light(),new Heavy())})(这个可能就是可变参数的原理吧)
要不写成Arrays.asList((Snow)new Light(),(Snow)new Heavy());