Java泛型和数组初始化 [英] Java generics and array initialization

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

问题描述

下面的解释是什么:

public class GenericsTest {
    //statement 1
    public ArrayList<Integer>[] lists;

    public GenericsTest()
    {
            //statement 2
        lists = new ArrayList<Integer>[4];
    }
}

编译器接受语句 1.语句 2 被编译器标记为通用数组创建".

The compiler accepts statement 1. Statement 2 is flagged by the compiler for "generic array creation".

我看到的关于禁止通用数组的一个很好的解释是这个,认为由于数组是协变的,而泛型不是,如果允许泛型数组,则可以颠覆泛型类型.

A good explanation I've seen regarding disallowing generic arrays is this one, arguing that since arrays are covariant and generics are not you could subvert the generic typing if you allowed generic arrays.

关于语言是否应该在泛型处理中制造这种复杂的不一致的极端长度的争论不谈,以防止你无论你多么努力地尝试(如果有人知道任何好的讨论)关于该问题的相对优点/缺点,请发表,我很想看看这些论点),如果(2)不是,为什么要允许声明(1)?

Leaving aside the argument over whether the language should go to the extreme lengths of creating this kind of complicated inconsistency in the treatment of generics to keep you from shooting yourself no matter how hard you try (and if anyone knows of any good discussions on the relative merits/demerits of the issue please post, I'd be interested to see the arguments), why should statement (1) be allowed if (2) isn't?

推荐答案

似乎有一些晦涩的情况,您可能会无意中导致 ClassCastException,如此处所述http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf(第 7.3 节)

There seems to be obscure cases where you could inadvertently cause a ClassCastException as explained here http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf (section 7.3)

可以在此处找到有关此主题的有趣讨论http://courses.csail.mit.edu/6.170/old-www/2006-Spring/forum/index.php%3Ftopic=324.msg1131.html

an intersting discussion on this topic could be found here http://courses.csail.mit.edu/6.170/old-www/2006-Spring/forum/index.php%3Ftopic=324.msg1131.html

这篇关于Java泛型和数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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