0

I know there is a similar quesion,but the answer is telling me how to do it but not the reason.And I have another way to create but I don't know why

public class testForGeneric<T> {

    public testForGeneric(T[] a) {
        int len = a.length;
        Node<T>[] nodes =  new Node<T>[len];//THE PROBLEM!
        for (int i = 0; i < len; i++) 
            nodes[i] = new Node<>(a[i], i);
    }

    public static void main(String[] args) {
        Integer[] a = { 3, 2, 4 };
        testForGeneric<Integer> t = new testForGeneric<>(a);
    }
}

The Error at the problem line is:

Cannot create a generic array of Node

Trial & Question

If you change the line to Node<T> nodes = new Node[len],that will be right. But you will get a warning:

Type safety: The expression of type Node[] needs unchecked conversion to conform to Node[]

I don't know why this is right.Node[len] is like some normal array.and from the warning,why the Node[] can convert to Node<T>[]?

and Why the element in array should initialized with Node<>()?

and if you using Object array casting to Node<T>[] array,that's also wrong.

the Node.java:

public class Node<T> {

    public T val;
    public int index;

    public Node(T val, int index) {
        this.index = index;
        this.val = val;
    }

    public Node() {
    }
}

THIS IS JUST A TEST FOR GENERIC ARRAY

I want to know why it's right or wrong.

jojo_007
  • 115
  • 1
  • 5
  • 1
    Possible duplicate of [Cannot create an array of LinkedLists in Java...?](https://stackoverflow.com/questions/217065/cannot-create-an-array-of-linkedlists-in-java) – FailingCoder Apr 19 '19 at 18:46
  • I think it's not and I have explain the reason at my first line. – jojo_007 Apr 26 '19 at 15:24

1 Answers1

0

You can't create an array of generics in Java.

You will find that a simple statement like this will not even compile because the Java compiler does not allow this. To understand the reason, you first need to know two arrays are covariant and generics are invariant.

Covariant: It means you can assign subclass type array to its superclass array reference.

Invariant: It means you cannot assign subclass type generic to its super class generic reference because in generics any two distinct types are neither a subtype nor a supertype.

Source

Community
  • 1
  • 1
devgianlu
  • 1,547
  • 13
  • 25