没有类型的ArrayList泛型 [英] ArrayList Generic without Type
问题描述
代码:
public class Solution {
public static void main(String args []){
ArrayList res = returnlist();
System.out.print(res.get(0));
}
public static ArrayList< ArrayList< Integer>> returnlist(){
ArrayList result = new ArrayList();
ArrayList<整数> content = new ArrayList< Integer>();
content.add(1);
result.add(content);
返回结果;
}}
我的问题是
为什么我们可以使用 ArrayList result = new ArrayList();
来创建一个对象,因为我们没有给这个集合的实际类型
result.add(content);
将集合添加到集合result的集合中只是一个普通的集合。我们还没有将它定义为 ArrayList
ArrayList
$ b解决方案
Java通用集合不会与类型一起存储以确保与J2SE 5.0之前的向后兼容性。类型信息在添加到通用集合时被删除。这被称为类型擦除。
这意味着泛型集合可以分配给非泛型引用。
所有Java泛型实际上都确保可以' t将错误的类型添加到通用列表中,并且可以避免执行显式在检索时投射;即使它仍然完成隐式。
继续
recently I read a piece of code which seems weird to me. As we know, we need to initialize the generic type in collections when we need to use them. Also, we know Collections can contain Collections as their elements.
The code:
public class Solution {
public static void main(String args[]) {
ArrayList res = returnlist();
System.out.print(res.get(0));
}
public static ArrayList<ArrayList<Integer>> returnlist() {
ArrayList result = new ArrayList();
ArrayList<Integer> content = new ArrayList<Integer>();
content.add(1);
result.add(content);
return result;
}}
My question is
- why can we use
ArrayList result = new ArrayList();
to create an object, since we have not gave the collection the actual type of element. - why can we use
result.add(content);
to add a collection to a collection with collection "result" is just a plain collection. We have not defined it as aArrayList
ofArrayList
Java generic collections are not stored with a type to ensure backwards compatibility with pre J2SE 5.0. Type information is removed when added to a generic collection. This is called Type Erasure.
This means that a generic collection can be assigned to a non generic reference.
All Java generics really does is make sure you can't add the wrong type to a generic list and saves you from doing an explicit cast on retrieval; even though it is still done implicitly.
Further to this
- the Java section of this answer goes a little deeper into what I just said
- this article also covers basically what you were asking in a more complete way
- other things to watch out for with Type Erasure
这篇关于没有类型的ArrayList泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!