【问题标题】:why does Java allow generic array declaration?为什么Java允许泛型数组声明?
【发布时间】:2019-06-22 14:09:17
【问题描述】:

我知道数组泛型数组创建是不允许的,因为数组需要在运行时知道它们的类型,但由于泛型在运行时擦除它们的类型信息,所以不可能创建泛型数组。 但是它为什么允许通用数组声明如下:

private E[] genericArray;// this line does not prevent the class from compiling

private E[] genericArrayTwo= new E[][10];// this line prevents the class from compiling

【问题讨论】:

  • 为什么不允许?注意,数组的字段声明默认初始化为null,所以不需要知道元素类型。

标签: java generic-programming generic-list


【解决方案1】:
private E[] genericArray;// this line does not prevent the class from compiling

private E[] genericArrayTwo= new E[][10];// this line prevents the class from compiling
  • 您的第一个示例是编译时评估,以确保正确 打字。简单地说,这个数组可能包含 E 类型的东西。
  • 当 E 具有 已经被抹去了。无法创建 E 类型的数组,因为 E 不再可用。

允许泛型数组声明可确保在编译时匹配适当的类型。

      Integer[] ints1 = null;
      String[] str1 = null;

      // both requires cast or it won't compile
      Integer[] ints = (Integer[])doSomething1(ints1);
      String[] str = (String[])doSomething1(str1);

      //but that could result in a runtime error if miscast.
      //That type of error might not appear for a long time

      // Generic method caters to all array types.
      // no casting required.
      ints = doSomething2(ints1);
      str = doSomething2(str1);

   }

   public static Object[] doSomething1(Object[] array) {
      return array;
   }

   public static <T> T[] doSomething2(T[] array) {
      return array;
   }

它允许以下示例:

public <T> void copy(List<T> list, T[] array) {
   for (T e : array) {
      list.add(e);
   }
}

然后,您可以将列表或数组中的值分配给某个类型为 T 的变量,而无需获得类转换异常或无需进行 instanceof 测试。

【讨论】:

  • “允许泛型数组声明确保在编译时匹配适当的类型”你能解释一下吗?
【解决方案2】:

如果E 是当前类的正式泛型,是的,你可以这样做:

List<E> e = new ArrayList<E>();

但你不能这样做:

E[] e = new E[10];

但是声明E[] e 变量同样有意义。

因为没有人阻止您从知道数组真实类型的客户端评估数组:

Foo<E> class{        
    private E[] array;
    Foo(E[] array) {
        this.array = array;
    }
}

并将其用作:

Foo<String> foo = new Foo<>(new String[] { "a", "b" });

或者作为替代方案,您也可以传递数组的类以从客户端实例化:

Foo<String> foo = new Foo<>(String.class);

所以你看到声明E[] array 并不是那么无助。

【讨论】:

    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2018-08-15
    • 2010-11-01
    相关资源
    最近更新 更多