如何在 Java 中创建通用数组? [英] How to create a generic array in Java?

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

问题描述

由于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?

我在 Java 论坛上看到了这样的解决方案:

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.

推荐答案

作为回报,我必须问一个问题:您的 GenSet 是选中"还是未选中"?这是什么意思?

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

  • 检查:强输入.GenSet 明确知道它包含什么类型的对象(即它的构造函数是用 Class 参数显式调用的,并且方法在传递参数时会抛出异常不是 E 类型.请参阅 Collections.checkedCollection.

  • 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];
        }
    
        ...
    }
    

  • 所有这些都源于 Java 中一个已知的、蓄意的、泛型的弱点:它是使用擦除实现的,所以泛型"类不知道它们在运行时创建的类型参数,因此不能除非实现了某种显式机制(类型检查),否则提供类型安全.

    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.

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

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