英文:
Why am I getting a ClassCastException when converting an arrayList of objects to an array of the same object?
问题
所以我对这些东西不太熟悉,而且今天也过得很长,所以我可能忽略了一些明显的东西,但这就是导致我的错误的原因。以下是完整的错误消息和导致错误的代码行。
> 异常线程“main”中的 java.lang.ClassCastException: 无法将类 [Ljava.lang.Object; 强制转换为类 [LenumAssignment.Student;([Ljava.lang.Object; 在加载程序“引导程序”的 java.base 模块中;[LenumAssignment.Student; 在加载程序“应用程序”的未命名模块中)
ArrayList<Student> s = nameObtain();
Student[] students = (Student[]) s.toArray();
英文:
So I'm not too experienced with these sort of things, and its also been a long day so I'm probably missing something obvious, but this is what is causing my error. Here is the error message in its entirety along with the lines that cause the error.
> Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [LenumAssignment.Student; ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; [LenumAssignment.Student; is in unnamed module of loader 'app')
ArrayList<Student> s = nameObtain();
Student[] students = (Student[]) s.toArray();
</details>
# 答案1
**得分**: 1
Method [`List::toArray()`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#toArray--) 返回 `Object[]`,无法直接转换为 `Student[]`(在这里有解释:[链接](https://stackoverflow.com/questions/395030/casting-an-array-of-objects-into-an-array-of-my-intended-class))
因此,你有<strike>两个</strike>三个选项:
1. 获取 `Object[] arr` 并将其元素转换为 `Student`
2. 使用类型安全的 [`List::toArray(T[] arr)`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#toArray-T:A-) 方法
3. 使用类型安全的 [`Stream::toArray`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#toArray-java.util.function.IntFunction-) 方法。
```java
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));
英文:
Method List::toArray()
returns Object[]
which cannot be simply cast to Student[]
(explained here)
So you have <strike>two</strike> three options:
- Get
Object[] arr
and cast its elements toStudent
- Use typesafe
List::toArray(T[] arr)
- Use typesafe
Stream::toArray
method.
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论