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

查看:440
本文介绍了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.

撇开争执语言是否应该去仿制药的治疗创造这种复杂矛盾的极端长度,让您从拍摄自己,无论你怎么努力(如果任何人任何良好的讨论都知道在这个问题上请张贴的相对优点/缺点,我很想看到参数),为什么要声明(1)如果(2)是不允许的?

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)

有关这个主题的野趣讨论可以在这里找到
<一href=\"http://courses.csail.mit.edu/6.170/old-www/2006-Spring/forum/index.php%3Ftopic=324.msg1131.html\" rel=\"nofollow\">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天全站免登陆