MAO-EYE 2009-02-09 17:30 采纳率: 100%
浏览 696
已采纳

如何在 Java 中创建泛型数组?

Due to the implementation of Java generics, you can't have code like this:

public class GenSet<E> {
    private E a[];

    public GenSet() {
        a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
    }
}

How can I implement this while maintaining type safety?

I saw a solution on the Java forums that goes like this:

import java.lang.reflect.Array;

class Stack<T> {
    public Stack(Class<T> clazz, int capacity) {
        array = (T[])Array.newInstance(clazz, capacity);
    }

    private final T[] array;
}

But I really don't get what's going on.

转载于:https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java

  • 写回答

29条回答 默认 最新

  • bug^君 2009-02-09 22:19
    关注

    I have to ask a question in return: is your GenSet "checked" or "unchecked"? What does that mean?

    • Checked: strong typing. GenSet knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class<E> argument, and methods will throw an exception when they are passed arguments that are not of type E. See Collections.checkedCollection.

      -> in that case, you should write:

      public class GenSet<E> {
      
          private E[] a;
      
          public GenSet(Class<E> c, int s) {
              // Use Array native method to create array
              // of a type only known at run time
              @SuppressWarnings("unchecked")
              final E[] a = (E[]) Array.newInstance(c, s);
              this.a = a;
          }
      
          E get(int i) {
              return a[i];
          }
      }
      
    • Unchecked: weak typing. No type checking is actually done on any of the objects passed as argument.

      -> in that case, you should write

      public class GenSet<E> {
      
          private Object[] a;
      
          public GenSet(int s) {
              a = new Object[s];
          }
      
          E get(int i) {
              @SuppressWarnings("unchecked")
              final E e = (E) a[i];
              return e;
          }
      }
      

      Note that the component type of the array should be the erasure of the type parameter:

      public class GenSet<E extends Foo> { // E has an upper bound of Foo
      
          private Foo[] a; // E erases to Foo, so use Foo[]
      
          public GenSet(int s) {
              a = new Foo[s];
          }
      
          ...
      }
      

    All of this results from a known, and deliberate, weakness of generics in Java: it was implemented using erasure, so "generic" classes don't know what type argument they were created with at run time, and therefore can not provide type-safety unless some explicit mechanism (type-checking) is implemented.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)