'How can we create T[] array in a method of a GenericClass<T>?

The below method is created in a Generic Class. I am quite new to Java so any pointers would be a great help.

public class LinkedList<T>{

public T[] toArray(){
        T[] array = (T[]) new Object[size];
        Node<T> curr = first;
        int index = 0;
        while (curr != null){
            array[index++] = curr.value;
            curr = curr.next;
        }
        return array;
    }

}

When I use this I get ClassCastException when I try to access the Main method like below.

public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
    var a = list.toArray();
    System.out.println(a.toString());
}

Below is the exception I am getting when executing the above code.

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Integer; ([Ljava.lang.Object; and [Ljava.lang.Integer; are in module java.base of loader 'bootstrap') at com.company.Main.main(Main.java:49)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source