项目中需要用一个List
接多种List<T>
。
这样写List<Object> list = getType1List();
编译不通过,提示获取的类型与指定的类型不匹配。
但是换成List list = getType1List();
就能编译通过了。这是为什么呢?
PHPz2017-04-17 17:26:05
Like List list = getType1List();
, this way of writing is the way it was written before Java did not have generics. This way of writing is type unsafe. Since there are no type parameters, what should be put in it? All types can be compiled and passed. List list = getType1List();
这种写法,是以前Java没有泛型的时候的写法,这种写法是类型不安全的,由于没有类型参数,所以往里面放什么类型都是可以编译通过的。
有了泛型以后一般都是推荐用泛型来写的,使用类型参数,List<Object> list = getType1List();
List<Object> list = getType1List();
Just like this, the compiler will check the type put in Is it consistent with the type parameter? If not, the compiler will report an error. 🎜