This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/5…

Issue an overview

Because of the implementation of generics in Java, you can’t

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

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

How can I do this without being type-safe

I saw an approach like this in the Java forums

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;
}
Copy the code

But I really don’t understand what’s going on, you know

Best answer

I have to ask a question: what does it mean to have your GenSet checked or unchecked?

Checked: strongly typed, GenSet knows exactly what type of object it contains. That is, its constructor explicitly calls a Class argument, and the method can throw an error if the passed argument is not type E. More look at the Collections. CheckedCollection)

-> In this case, this is what you should do

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) {
        returna[i]; }}Copy the code

Unchecked: weak type, no type checking, requires type as an argument -> in which case you should do this

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];
        returne; }}Copy the code