简体   繁体   English

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

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

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;线程“main”中的异常 java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [LenumAssignment.Student;不能转换为类 [LenumAssignment.Student; ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; [LenumAssignment.Student; is in unnamed module of loader 'app') ([Ljava.lang.Object; 位于加载器“bootstrap”的 java.base 模块中;[LenumAssignment.Student; 位于加载器“app”的未命名模块中)

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

Method List::toArray() returns Object[] which cannot be simply cast to Student[] (explained here )方法List::toArray()返回不能简单地转换为Student[] Object[] Student[] (解释here

So you have two three options:所以你有 两个 三个选项:

  1. Get Object[] arr and cast its elements to Student获取Object[] arr并将其元素转换为Student
  2. Use typesafe List::toArray(T[] arr)使用类型安全List::toArray(T[] arr)
  3. Use typesafe Stream::toArray method.使用类型安全的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