有一个ClassCastException,我不知道为什么不能将Object[]转换成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>{
...
}
当我运行代码时,我得到了 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)
最佳答案
为什么 Student[] sList = (Student[]) pList.toArray();
不起作用?
来自下方链接的一些信息:
In Java, generic type exists at compile-time only. At runtime information about generic type (like in your case
Student
) is removed and replaced withObject
type (take a look at type erasure). That is why at runtimetoArray()
have no idea about what precise type to use to create new array, so it uses Object as safest type, because eachclass 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()) toStudent[]
. To let it know what your desired object type is, you can pass a typed array intotoArray()
.
解决方案:pList.toArray(Student[]::new)
关于java - 为什么当我尝试将 object[] 转换为 Student[] 时出现 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62861969/