3

there is a ClassCastException,I don't know why 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 the 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)

MD.Luffy
  • 35
  • 5

1 Answers1

3

Why Student[] sList = (Student[]) pList.toArray(); wont work?

Some info from the link right 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 info: Converting 'ArrayList<String> to 'String[]' in Java

Clashsoft
  • 11,553
  • 5
  • 40
  • 79
Antaaaa
  • 233
  • 3
  • 14