1

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();
YungQC
  • 13
  • 3
  • Could you please provide a few more details? How is `nameObtain()` definied? Somewhere you try to convert "Object" to "Student" and that fails. – Sztyler Oct 23 '20 at 22:18
  • 2
    Possible duplicate of [this](https://stackoverflow.com/q/1115230/11882002). `toArray` returns an `Object[]`, so you'll need `s.toArray(new Student[0])` or something like that – user Oct 23 '20 at 22:22

1 Answers1

1

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));
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42