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();
2
  • Could you please provide a few more details? How is nameObtain() definied? Somewhere you try to convert "Object" to "Student" and that fails. Commented Oct 23, 2020 at 22:18
  • 2
    Possible duplicate of this. toArray returns an Object[], so you'll need s.toArray(new Student[0]) or something like that Commented Oct 23, 2020 at 22:22

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.