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

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

问题描述

Java不允许我们这样做的原因是什么

What's the reason why 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天全站免登陆