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

Time:02-14

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)

CodePudding user response:

Thanks for the pointer Turing85 to List Java docs. I got my code working.

public class LinkedList<T>{
public T[] toArray(T[] type){ //Made a change here from the Original code
        Node<T> curr = first;
        int index = 0;
        while (curr != null){
            type[index  ] = curr.value;
            curr = curr.next;
        }
        return (T[]) type;
    }
}

Main Method:

public static void main(String[] args) {
    LinkedList<Integer> list = new LinkedList<Integer>();
    var a = list.toArray(new Integer[list.getSize()]); //Made a change here
    System.out.println(Arrays.toString(a));
}
  • Related