I have an error using Java Collections in JDK 1.7 : I got this Exception in this line: proposalStatuses.addAll(getAllSubmittedStatuses())
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractCollection.addAll(Unknown Source)
trying to add a collection to a list
/**
* Gets the all submitted statuses.
*
* @return the all submitted statuses
*/
private Collection<ProposalStatus> getAllSubmittedStatuses() {
return Arrays.asList(
ProposalStatus.SAVED_TO_IOS
, ProposalStatus.SENDED_TO_IOS_IN_PROGRESS
);
}
/**
* Gets the all received statuses.
*
* @return the all received statuses
*/
private Collection<ProposalStatus> getAllReceivedStatuses() {
Collection<ProposalStatus> proposalStatuses =
Arrays.asList(
ProposalStatus.RECEIVED_BY_IOS
, ProposalStatus.SUBMITTED_TO_IOS
, ProposalStatus.RECEIVED_IOS
);
proposalStatuses.addAll(getAllSubmittedStatuses());
return proposalStatuses;
}
The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList , which can be modified. An unmodifiable collection or data structure should not be attempted to be modified.
The Java. util. List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
There are two methods to add elements to the list. add(E e ) : appends the element at the end of the list. Since List supports Generics , the type of elements that can be added is determined when the list is created. add(int index , E element ) : inserts the element at the given index .
asList returns a fixed size List backed by an array. Therefore remove and add are not supported.
From the javadoc of Arrays.asList()
(emphasis mine):
Returns a fixed-size list backed by the specified array
In short: you cannot .add*()
or .remove*()
from such a List! You'll have to use another modifiable List implementation (ArrayList
for instance).
Arrays.asList()
returns an immutable list, that you cannot modify.
More specifically, add(), addAll() and remove() methods are not implemented.
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