【问题标题】:Why am I getting a ClassCastException when converting an arrayList of objects to an array of the same object?将对象的arrayList 转换为同一对象的数组时,为什么会出现 ClassCastException?
【发布时间】:2020-10-23 22:11:53
【问题描述】:

所以我对这类事情没有太多经验,而且这也是漫长的一天,所以我可能遗漏了一些明显的东西,但这就是导致我的错误的原因。以下是完整的错误消息以及导致错误的行。

线程“main”中的异常 java.lang.ClassCastException: class [Ljava.lang.Object;不能转换为类 [LenumAssignment.Student; ([Ljava.lang.Object; 在加载器“bootstrap”的模块 java.base 中;[LenumAssignment.Student; 在加载器“app”的未命名模块中)

ArrayList<Student> s = nameObtain();
Student[] students = (Student[]) s.toArray();

【问题讨论】:

  • 能否提供更多细节? nameObtain() 是如何定义的?在某处您尝试将“对象”转换为“学生”但失败了。
  • this 的可能重复项。 toArray 返回一个Object[],所以你需要s.toArray(new Student[0]) 或类似的东西

标签: java arrays


【解决方案1】:

方法List::toArray()返回Object[],不能简单地转换为Student[](解释为here

所以你有两个三个选项:

  1. 获取Object[] arr 并将其元素转换为Student
  2. 使用类型安全List::toArray(T[] arr)
  3. 使用类型安全的Stream::toArray 方法。
List<Student> list = Arrays.asList(new Student(), new Student(), new Student());
Object[] arr1 = list.toArray();
        
for (Object a : arr1) {
    System.out.println("student? " + (a instanceof Student) + ": " + (Student) a);
}
        
Student[] arr2 = list.toArray(new Student[0]);
        
System.out.println(Arrays.toString(arr2));

Student[] arr3 = list.stream().toArray(Student[]::new);
System.out.println(Arrays.toString(arr3));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 2020-10-29
    • 2013-02-21
    • 1970-01-01
    相关资源
    最近更新 更多