程序go 2009-02-09 17:30 采纳率: 100%
浏览 524
已采纳

如何在 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条回答 默认 最新

  • 喵-见缝插针 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条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图