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 b开发者_C百科etter 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());
It depends on the actual implementation of List
.
e.g if the underlying list was obtained using Collections.unmodifiableList() then calling addAll()
or any other modification method will throw an UnsupportedOperationException
.
When it throws an exception, it should show you the exact line number and source code file - you should be able to find out exactly why it's throwing an exception.
My guess is that under certain circumstances, eventTable.getEvents()
returns an immutable list, or something like that - but without knowing what eventTable
is, it's hard to say for sure. If you can produce a short but complete program which demonstrates the problem, that would make it a lot easier to diagnose.
精彩评论