创建通用集合的数组 [英] Creating an array of generic collections
问题描述
其实,问题应该是
创建一个通用的数组。
为什么编译器不能处理?
以下内容将被标记为错误 - 无法创建通用数组。
列表< MyDTO> [] dtoLists = {new ArrayList< MyDTO>(),anExistingDtoList};
为了克服这个问题,我需要
List< MyDTO> [] dtoLists =(List< MyDTO> [])Array.newInstance(ArrayList.class,2);
dtoLists [0] = new ArrayList< MyDTO>();
dtoLists [1] = anExistingDtoList;因此,为什么编译器不能将第一种情况转换为第二种情况?
我意识到泛型是编译时确定的,而不是运行时确定的,而数组是运行时确定的,因此需要一个确定类型来创建数组。 p>
编译器设计者将遇到的技术/逻辑障碍会阻止他们实现这一点?
问题纯粹哲学,关于语言正交性?如果是这样,这样的行为如何违反语言正交性?
这是一个复杂的问题吗?解释复杂性。
我希望我的问题的答案能让我更好地了解java编译器在涉及泛型时的行为。
附注:
c'mon停止被触发快乐。答案通用列表数组
不回答我的问题。为什么编译器不能自动执行转换?
解决方案实际上,Java会为varargs创建通用数组,可以做
List< MyDTO> [] dtoLists = array(new ArrayList< MyDTO>(),anExistingDtoList);
@SafeVarargs
static< E> E [] array(E ... array)
{
return array;
}
至于为什么明确的通用数组创建被禁止,它有什么关系类型擦除。 (在上面的解决方案中存在相同的问题,但由 @SafeVarargs
抑制)但是它是有争议的;有不同的方式来处理这个问题,编译器警告可能就足够了。但是他们选择彻底禁止它,可能是因为数组已不再重要,现在我们有通用集合
Actually, the question should be
Creating an array of generic anything.
Why can't the compiler take care of it?
The following would be flagged as an error - cannot create generic array.
List<MyDTO>[] dtoLists = {new ArrayList<MyDTO>(), anExistingDtoList};
To overcome that, I need to
List<MyDTO>[] dtoLists = (List<MyDTO>[])Array.newInstance(ArrayList.class, 2);
dtoLists[0] = new ArrayList<MyDTO>();
dtoLists[1] = anExistingDtoList;
So, why can't the compiler convert the first case into the second case?
I do realise that generics are compile-time determinate and not run-time determinate, while arrays are run-time determinate and therefore need a determinate type in order to create an array.
What are the technological/logical barriers compiler designers would encounter that would prevent them being able to implement this?
Is the issue purely philosophical, concerning language orthogonality? If so, how would such a behaviour violate language orthogonality?
Is it a question of complexity? Explain the complexity.
I am hoping answers to my question would give me better insight into java compiler behaviour when it concerns generics.
Side note:
c'mon stop being trigger happy. The answers Array of Generic List
do not answer my question. Why can't compilers spontaneously perform the conversion?
解决方案 Actually Java does create generic array for varargs, so you can do
List<MyDTO>[] dtoLists = array(new ArrayList<MyDTO>(), anExistingDtoList);
@SafeVarargs
static <E> E[] array(E... array)
{
return array;
}
As to why is explicit generic array creation forbidden, it has something to do with type erasure. (The same concern exists in the above solution, but suppressed by @SafeVarargs
) However it is debatable; there are different ways to handle the concern, a compiler warning is probably enough. But they chose to outright ban it, probably because arrays are no longer important anyway now that we have generic collections
这篇关于创建通用集合的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!