Java UnsupportedOperationException with collection objects

I have a bug using Java Collections in JDK 1.7: I got this exception on this line: the Stats.addAll clause (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 the 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; } 
+5
source share
3 answers

From javadoc Arrays.asList() (focus):

Returns a fixed size list supported by the specified array

In short: you cannot .add*() or .remove*() from such a list! You will have to use another modifiable implementation of List ( ArrayList , for example).

+11
source

To clarify a bit more, I use your code:

 private Collection<ProposalStatus> getAllSubmittedStatuses() { // This returns a list that cannot be modified, fixed size 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() { // proposalStatuses will be a fixed-size list so no changing Collection<ProposalStatus> proposalStatuses = Arrays.asList( ProposalStatus.RECEIVED_BY_IOS , ProposalStatus.SUBMITTED_TO_IOS , ProposalStatus.RECEIVED_IOS ); // This will not be possible, also you cannot remove anything. proposalStatuses.addAll(getAllSubmittedStatuses()); return proposalStatuses; } 

For your purpose, I would do the following:

 return new ArrayList<ProposalStatus>(Arrays.asList(ProposalStatus.SAVED_TO_IOS,ProposalStatus.SENDED_TO_IOS_IN_PROGRESS) 

This will help you get Collection objects.

+1
source

Arrays.asList() returns an immutable list that you cannot change.

In particular, the add (), addAll (), and remove () methods are not implemented.

+1
source

Source: https://habr.com/ru/post/1211622/


All Articles