I have a code that read list from some paged string data. What I do not understand - why the UnsupportedOperationException is thrown on addAll() and why it's kind of random behaviour ?
I know creating target ArrayList and not adding to the returned one solves the issue, I'm looking for better understanding not a fix.
List<Event> eventList = eventTable.getEvents(); // returns ArrayList
while (hasNextPage()) {
goToNextPage();
eventList.addAll(eventTable.getEvents());
}
List<Event>
is not necessarily an ArrayList<Event>
. (The opposite is true though.)
The reason you get UnsupportedOperationException
sometimes, is because eventTable.getEvents()
sometimes returns a list that supports addAll
and sometimes it doesn't.
The implementation of getEvents
could for instance look like this:
if (noEventsAvailable) {
return Collections.emptyList();
} else {
List<Event> toReturn = new ArrayList<Event>();
// populate list...
return toReturn;
}
(In your comment you write // returns ArrayList
. I don't know where you've got this from, but I know one thing for sure: An ArrayList
will always support the addAll
operation.)
The correct way to solve it is, as you mention, to do
List<Event> eventList = new ArrayList<Event>(eventTable.getEvents());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With