Java不允许我们这么做的原因是什么
private T[] elements = new T[initialCapacity];
我可以理解。net不允许我们这样做,因为在。net中,值类型在运行时可以有不同的大小,但在Java中,所有类型的T都将是对象引用,因此具有相同的大小(如果我错了请纠正我)。
原因是什么?
Java不允许我们这么做的原因是什么
private T[] elements = new T[initialCapacity];
我可以理解。net不允许我们这样做,因为在。net中,值类型在运行时可以有不同的大小,但在Java中,所有类型的T都将是对象引用,因此具有相同的大小(如果我错了请纠正我)。
原因是什么?
当前回答
在我的例子中,我只是想要一个堆栈数组,就像这样:
Stack<SomeType>[] stacks = new Stack<SomeType>[2];
由于这是不可能的,我使用了以下作为解决方案:
创建一个非泛型包装器类围绕堆栈(例如MyStack) MyStack[] stacks = new MyStack[2]工作得很好
丑陋,但Java是快乐的。
注意:正如BrainSlugs83在问题的评论中提到的,在.NET中完全可以有泛型数组
其他回答
在我的例子中,我只是想要一个堆栈数组,就像这样:
Stack<SomeType>[] stacks = new Stack<SomeType>[2];
由于这是不可能的,我使用了以下作为解决方案:
创建一个非泛型包装器类围绕堆栈(例如MyStack) MyStack[] stacks = new MyStack[2]工作得很好
丑陋,但Java是快乐的。
注意:正如BrainSlugs83在问题的评论中提到的,在.NET中完全可以有泛型数组
T vals [];/ /好吧
但是,你不能实例化T的数组 // vals = new T[10];//不能创建T的数组
你不能创建T的数组的原因是没有办法 编译器来了解实际创建的数组类型。
Oracle教程:
You cannot create arrays of parameterized types. For example, the following code does not compile: List<Integer>[] arrayOfLists = new List<Integer>[2]; // compile-time error The following code illustrates what happens when different types are inserted into an array: Object[] strings = new String[2]; strings[0] = "hi"; // OK strings[1] = 100; // An ArrayStoreException is thrown. If you try the same thing with a generic list, there would be a problem: Object[] stringLists = new List<String>[]; // compiler error, but pretend it's allowed stringLists[0] = new ArrayList<String>(); // OK stringLists[1] = new ArrayList<Integer>(); // An ArrayStoreException should be thrown, // but the runtime can't detect it. If arrays of parameterized lists were allowed, the previous code would fail to throw the desired ArrayStoreException.
对我来说,这听起来很软弱。我认为任何对泛型有充分理解的人,都完全可以理解,甚至期望,在这种情况下ArrayStoredException不会被抛出。
这是不可能的,因为Java完全在编译器级别上实现了泛型,并且每个类只生成一个类文件。 这叫做类型擦除。
在运行时,已编译的类需要用相同的字节码处理它的所有使用。因此,new T[capacity]将完全不知道需要实例化什么类型。
这是因为Java的数组(与泛型不同)在运行时包含关于其组件类型的信息。因此,在创建数组时必须知道组件类型。因为您不知道T在运行时是什么,所以您不能创建数组。