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

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

问题描述

最近我读了一段对我来说很奇怪的代码.众所周知,当我们需要使用集合时,我们需要初始化集合中的泛型类型.此外,我们知道集合可以包含集合作为它们的元素.

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.

代码:

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;
}}

我的问题是

  • 为什么我们可以使用 ArrayList result = new ArrayList(); 来创建一个对象,因为我们没有为集合提供元素的实际类型.
  • 为什么我们可以使用 result.add(content); 将一个集合添加到一个集合中,而集合result"只是一个普通的集合.我们还没有把它定义为ArrayList
  • ArrayList
  • 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 泛型集合不与类型一起存储,以确保向后兼容 J2SE 5.0 之前的版本.添加到泛型集合时,类型信息将被删除.这称为类型擦除.

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 and objects in a generic typed collection can be placed in an non generic, nontyped collection.

所有 Java 泛型真正做的就是确保您不能将错误的类型添加到泛型列表中,并避免您执行 explicit 在检索时强制转换;即使它仍然隐式.

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.

更进一步

  • 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屋!

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