How do I create a generic array in Java?

Asked 2 years ago, Updated 2 years ago, 141 views

Due to the Java generic implementation, it cannot be implemented as follows:

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

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

How can I implement it while maintaining the type of safety?

Previously, we looked for the following solutions in the Java Forum:

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 don't really understand how the source code above works. Help me.

reflection java generics array instantiation

2022-09-22 21:36

1 Answers

I will explain the answers to the questions in turn.

Is the class GenSet checked? Is it "unchecked"? Do you know the meaning of that?

If you define this case, you can implement it with the following code:

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

When defined as such, the following code can be implemented:

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 variable type in the array must be type erase for the type parameter. Type erasure is that type information in the source code is removed at compile time because it is unnecessary at runtime.

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

    ...
}

This is the weakness of Java generic. Since the "Generic" class does not know what type is specified during execution, it should be implemented as a type erase. Therefore, the safety of the type cannot be guaranteed unless some clear mechanisms such as type checking are implemented.


2022-09-22 21:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.