我在JDK 1.7中使用Java Collections时出错: 我在这一行中得到了这个例外: 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)
尝试将一个集合添加到列表中
/**
* 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;
}
答案 0 :(得分:11)
来自javadoc of Arrays.asList()
(强调我的):
返回由指定数组
支持的固定大小列表
简而言之:您不能从此类列表中.add*()
或.remove*()
!您将不得不使用另一个可修改的List实现(例如ArrayList
)。
答案 1 :(得分:1)
为了解释一下,我正在使用你的代码:
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;
}
出于您的目的,我会执行以下操作:
return new ArrayList<ProposalStatus>(Arrays.asList(ProposalStatus.SAVED_TO_IOS,ProposalStatus.SENDED_TO_IOS_IN_PROGRESS)
这可以帮助您获取Collection对象。
答案 2 :(得分:1)
Arrays.asList()
返回一个您无法修改的不可变列表。
更具体地说,没有实现add(),addAll()和remove()方法。