java - 为什么当我尝试将 object[] 转换为 Student[] 时出现 ClassCastException?

标签 java classcastexception

有一个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 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().

解决方案:pList.toArray(Student[]::new)

更多信息:Converting 'ArrayList<String> to 'String[]' in Java

关于java - 为什么当我尝试将 object[] 转换为 Student[] 时出现 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62861969/

相关文章:

java - 使用 Jersey JAX-RS 将 Jackson 注册为媒体类型 "text/plain"的消息正文阅读器

java - 如何将以下 Java 代码转换为 Node.js?

java - 转换为与实际类不同的泛型时没有 ClassCastException

Java:检测返回对象的类型

java - ClassCastException 从数据库中的组合框中插入数据

java - 将 Object[] 转换为 java 中的引用类型数组

java-正则表达式 : How to write regular expression for two digit numbers

Java数据文件在类之间共享

java - Eclipse - Android - 无法调试

java - Android:Button 类的 ClassCastException