什么是Java中的泛型数组的最简单的方法吗? [英] What is the easiest alternative to a generic array in Java?

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

问题描述

假设我有这样的:

class test<T>
{
    private T[] elements;
    private int size;
    public test(int size)
    {
        this.size = size;
        elements = new T[this.size];
    }
}

看来这是不可能的,因为编译器不知道一旦它试图取代仿制药code或东西叫什么构造函数。我想知道的是,我怎么会去这样做?我想这是可能的,给了它在C ++中如何轻松完成。

It seems this isn't possible because the compiler doesn't know what constructor to call once it tries to replace the generics code or something. What I'm wondering is, how would I go about doing this? I imagine it is possible, given how easily done it is in C++.

编辑:对不起,我忘了[]中的元素声明

Sorry I forgot the [] in the elements declaration.

推荐答案

现在的问题是,既然泛型类型参数 T 转化为对象由编译器(这就是所谓的类型擦除的)时,实际上创建对象的数组。你可以做的是提供一个类&LT; T&GT; 的功能:

The problem is that since the generic type parameter T is transformed into Object by the compiler (it's called type erasure), you actually create an array of Object. What you can do is provide a Class<T> to the function:

class test<T>
{
    private T[] elements;
    private int size;
    public test(Class<T> type, int size)
    {
        this.size = size;
        elements = (T[]) Array. newInstance(type, size);
    }
}

您会发现在这里更好的exlanation:<一href=\"http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#Can%20I%20create%20an%20array%20whose%20component%20type%20is%20a%20type%20parameter?\"相对=nofollow>安格莉卡兰格 - 我可以创建一个数组,其组件类型为类型参数

You will find a better exlanation of it here: Angelika Langer - Can I create an array whose component type is a type parameter?

这篇关于什么是Java中的泛型数组的最简单的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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