繁体   English   中英

将对象的数组列表转换为同一对象的数组时,为什么会出现 ClassCastException?

[英]Why am I getting a ClassCastException when converting an arrayList of objects to an array of the same object?

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

线程“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();

方法List::toArray()返回不能简单地转换为Student[] 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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM