如何创建通用数组? [英] How to create generic array?

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

问题描述


可能重复:

Java如何:通用数组创建

如何在Java中创建类型为 T [] 的数组?我无法使用 Arrays.newInstance(),因为我没有 Class< T> 的对象。在某个地方有 newInstance 的通用版本吗?

How to create an array of type T[] in Java? I can't use Arrays.newInstance() since I have no objects of Class<T>. Is there a generic version of newInstance somewhere?

我的方法原型如下:

public <T> T[][] distribute(T ... balls) {
   T[][] answer = ????

   // filling answer with data

   return answer;

}

更新

抱歉,在上面的示例中,我可以从上课。但假设我没有这样的变量。

Sorry in example above I can take class from balls. But suppose I have no such a variable.

public <T> T[][] distribute() {
   T[][] answer = ????

   // filling answer with data

   return answer;

}

class<T> {
   public T[][] distribute() {

      T[][] answer = ????

      // filling answer with data

      return answer;

   }
}

UPDATE2

此示例也不起作用:

public abstract class GenericArray<T> {

abstract public T create();

public T[] gen1() {
    T[] ans = (T[]) new Object[3];
    ans[0] = create();
    ans[1] = create();
    ans[2] = create();
    return ans;
}

public Integer[] gen2() {
    Integer[] ans = new Integer[3];
    ans[0] = new Integer(0);
    ans[1] = new Integer(0);
    ans[2] = new Integer(0);
    return ans;
}

public static void main(String[] args) {

    GenericArray<Integer> a = new GenericArray<Integer>() {

        @Override
        public Integer create() {
            return new Integer(0);
        }
    };

    Integer[] b = a.gen2();
    Integer[] c = a.gen1(); // this causes ClassCastException

    System.out.println("done");

}

}


推荐答案

1。数组不是 $ c>

1. Arrays are Not Generic

2。。这就是在检查过程中检查了数组的原因编译以及运行时,其中集合可以通用,并且仅在编译时进行检查 > ....

2. Thats the reason Arrays are checked during compile as well as runtime, where as Collections can be Generic and its checked only during the compile time....

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

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