我们可以创建一个通用类数组吗? [英] Can we create an Array of Generic class?

查看:60
本文介绍了我们可以创建一个通用类数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Java方法:通用数组创建

我想创建一个包含10个元素的Stack,我正在尝试使用泛型来实现.我首先创建了Type T的Stack类,但是在尝试实例化泛型类型的数组时遇到编译错误.

I want to create a Stack which contains 10 elements, I'm trying to do this with Generics. I started by creating a Stack class of Type T, but I'm getting compilation error when I try to instantiate the array of generic type.

public class Stack<T>{
    private T[] stk = new T[10];
}

我在这里做错了什么?

推荐答案

您不能这样做.并非没有对代码进行一些修改,即使如此,您最终还是必须进行 unsafe 强制转换,这完全破坏了尝试首先确保类型安全的全部原因.

You can't do this. Not without using some hacky round about code, and even then you have to do an unsafe cast in the end that completely ruins the entire reason for trying to be type safe in the first place.

这是因为Java具有一种称为类型擦除的东西,编译器会丢弃所有通用信息,并且运行时不知道 T 是什么.

This is because Java has something called type erasure, the compiler throws away all the generic information and the runtime doesn't know what T is.

这是执行此操作的首选方式:

Here is the preferred way of doing this:

@SuppressWarnings("unchecked")
static <T> T[] newArray(Class<T> type, int length)
{
    return (T[]) java.lang.reflect.Array.newInstance(type, length);
}

这不会在对 List< T> 实现黑客进行调用 toArray()的天真的解决方案中创建抛出列表实例.

This doesn't create the throw about list instance in the naive solution of calling toArray() on a List<T> implementation hack.

有关此的更多讨论,请参见

For more discussion on this see

此处是有关创建在运行时输入安全数组.

这篇关于我们可以创建一个通用类数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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