简体   繁体   中英

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; 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();

Method List::toArray() returns Object[] which cannot be simply cast to Student[] (explained here )

So you have two three options:

  1. Get Object[] arr and cast its elements to Student
  2. Use typesafe List::toArray(T[] arr)
  3. 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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