没有类型的ArrayList泛型 [英] ArrayList Generic without Type

查看:161
本文介绍了没有类型的ArrayList泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我读了一段看起来很奇怪的代码。正如我们所知道的,当我们需要使用它们时,我们需要在集合中初始化泛型类型。此外,我们知道Collections可以包含Collections作为其元素。



代码:

  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 a ArrayList of ArrayList

    解决方案

    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

    这篇关于没有类型的ArrayList泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆