我无法在Java中创建通用数组类型的原因是什么? [英] What's the reason I can't create generic array types in Java?

查看:205
本文介绍了我无法在Java中创建通用数组类型的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java不允许我们执行的原因是什么?

What's the reason Java doesn't allow us to do

private T[] elements = new T[initialCapacity];

我可以理解.NET不允许我们这样做,因为在.NET中您有价值类型在运行时可以有不同的大小,但在Java中,所有类型的T都将是对象引用,因此具有相同的大小(如果我错了,请纠正我)。

I could understand .NET didn't allow us to do that, as in .NET you have value types that at run-time can have different sizes, but in Java all kinds of T will be object references, thus having the same size (correct me if I'm wrong).

原因是什么?

推荐答案

这是因为Java的数组(不同于泛型)在运行时包含有关其组件类型。所以当你创建数组时,你必须知道组件的类型。由于您不知道 T 在运行时,您无法创建数组。

It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what T is at runtime, you can't create the array.

这篇关于我无法在Java中创建通用数组类型的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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