Java – Why do I get a ClassCastException when I try to convert object[] to Student[]?

Why do I get a ClassCastException when I try to convert object[] to Student[]?… here is a solution to the problem.

Why do I get a ClassCastException when I try to convert object[] to Student[]?

There is a ClassCastException, I wonder why I can’t convert Object[] to String[]?

package day5;

import java.util.ArrayList;
import java.util.Arrays;

public class JavaLog {
    public static void main(String[] args) throws Exception {
        ArrayList<Student> pList = new ArrayList<>();
        pList.add(new Student("Bob", 89));//Student("name", age)
        pList.add(new Student("Mike", 78));
        pList.add(new Student("John", 99));

Student[] sList = (Student[]) pList.toArray();
        Arrays.sort(sList);
        System.out.println(Arrays.toString(sList));
    }
}

class Student implements Comparable<Student>{
    ...
}

When I run the code, I get ClassCastException:

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Lday5.Student; ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; [Lday5.Student; is in unnamed module of loader 'app')
    at day5. JavaLog.main(JavaLog.java:13)

Solution

Why Student[]

sList = (Student[]) pList.toArray(); Not working?

Some information from the link below:

In Java, generic type exists at compile-time only. At runtime
information about generic type (like in your case Student) is
removed and replaced with Object type (take a look at type erasure).
That is why at runtime toArray() have no idea about what precise type
to use to create new array, so it uses Object as safest type, because
each class extends Object so it can safely store instance of any
class.

Now the problem is that you can’t cast instance of Object[] to Student[].

The JVM doesn’t know (or more precisely, it is not allowed to do that. If it could do that, it would violate Java type safety) how to blindly downcast Object[] (the result of
toArray()) to Student[]. To let it know what your desired object type
is, you can pass a typed array into toArray().

Solution: pList.toArray(Student[]::new).

More information: <a href=”https://stackoverflow.com/questions/4042434/converting-arrayliststring-to-string-in-java” rel=”noreferrer noopener nofollow”>Converting ‘ArrayList< String> to ‘String[]’ in Java

Related Problems and Solutions