参数化类型数组 [英] array of parameterized types

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

问题描述

  ArrayList< Pair< ParseNode, ParseNode>> [] nodes = new ArrayList [indexes.length]; 

为什么要复制< Pair< ParseNode,ParseNode>> 不合法?

解决方案

混凝土参数化类型的阵列天生就被破坏了。记住数组是协变的,数组类型检查是一个运行时操作。在运行时,所有泛型都被擦除,因此Array Store检查不能从< code>< Pair<< / code>< ;< BigInteger,IOException>>>



泛型的基本契约是I,编译器,代码不会产生任何警告,你永远不会在运行时得到类转换异常。



编译器也不能保证它能够给你一个编译如果不是 ArrayList< Pair< ParseNode,ParseNode>>< / code>被放入该数组中,则发生时间错误。运行时系统如果添加了错误的类型,也不能保证你会得到一个ArrayStoreException(就像Language Specification所说的那样),而不是以后在你将它取出时发生ClassCastException。 (第二部分实际上是为什么它实际上是非法的,而不仅仅是一个警告,它会导致一个数组不符合语言规范。)



所以它不会不要让你这样宣布,并强迫你承认'不安全'的警告。这样,它说:我告诉过你,我不能保证不会因为使用这个数组而导致任何类抛出异常,这是对你来说确保你只把正确的东西放在这里。


I'm having trouble figuring out what type parameter is expected at RHS of the following

ArrayList<Pair<ParseNode,ParseNode>>[] nodes = new ArrayList[indexes.length];

Why a copy of <Pair<ParseNode,ParseNode>> is not legitimate?

解决方案

Arrays of concrete paramaterized types are inherently broken. Remember arrays are covariant and the array type check is a runtime operation. At runtime all the generics have been type erased, so the Array Store check can't tell <Pair<ParseNode, ParseNode>> from <Pair<BigInteger,IOException>>.

The fundamental contract of a generic is "I, the compiler, promise that if you write code that generates no warnings, you will never get a class cast exception at runtime."

Neither can the compiler guarantee to you that it will be able to give you a compile time error if something that is not an ArrayList<Pair<ParseNode,ParseNode>> is put into that array. Nor can the runtime system guarantee you will get an ArrayStoreException (like the Language Specification says it will) if you add the wrong type, rather than a ClassCastException later when you take it back out. (The second part is really why it's actually illegal rather than just a warning, it would result in an array that doesn't obey the language specification.)

So it doesn't let you declare them that way and forces you to acknowledge the 'unsafe' warning. That way it has said "I told you I can't guarantee there will not be any class cast exceptions as a result of using this array, it's on you to make sure you only put the right things in here."

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

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