Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList.addAll(ArrayList) throws SOMETIMES UnsupportedOperationException

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());
}
like image 765
Rostislav Matl Avatar asked Aug 29 '11 12:08

Rostislav Matl


1 Answers

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());
like image 165
aioobe Avatar answered Sep 30 '22 15:09

aioobe