It states : "Cannot cast from List to ArrayList"
for :
return (ArrayList) eventRepository.findAll();
Why?
CodePudding user response:
Try the following:
List<Integer> a = new LinkedList<>();
a.add(1);
a.add(2);
a.add(3);
// throw "ClassCastException"
ArrayList<Integer> b = (ArrayList<Integer>) a;
System.out.println(b);
// approach 1: use "addAll"
ArrayList<Integer> c = new ArrayList<>();
c.addAll(a);
System.out.println(c); // [1, 2, 3]
// approach 2: feed directly when creating instance
ArrayList<Integer> d = new ArrayList<>(a);
System.out.println(d); // [1, 2, 3]
CodePudding user response:
You attempting to downcast from a more general type (List) to a more specific type (ArrayList). The compiler allows it at compile time, because it might succeed: the returned list might be an ArrayList after all.
But at runtime, what if the returned list is not of type ArrayList? What if it is actually, for example, a LinkedList? Then at runtime, the cast to ArrayList will fail.
Do you have to have the returned list be an ArrayList? Typically, you can interact with all the behaviors present with just the List interface without ever having to deal with the specifics of an ArrayList.
CodePudding user response:
I assume that you are using a CrudRepository
for your eventRepository.
This Class returns an Iterable, wich is not castable to ArrayList.
You can solve that problem in 2 ways:
The first solution would be to overwride the Repository like so
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface EventRepository extends CrudRepository<Event, Long> {
// you can even you ArrayList as return, but i would recomment List
List<Event> findAll();
}
The second solution would be to convert the Iterable to a List, for that you can simply follow this tutorial https://www.baeldung.com/java-iterable-to-collection