2015-01-21 14 views
5

Tôi có một lỗi sử dụng Java Collections trong JDK 1.7: tôi có ngoại lệ này ở dòng này: proposalStatuses.addAll (getAllSubmittedStatuses())Java UnsupportedOperationException với Bộ sưu tập các đối tượng

java.lang.UnsupportedOperationException 
     at java.util.AbstractList.add(Unknown Source) 
     at java.util.AbstractList.add(Unknown Source) 
     at java.util.AbstractCollection.addAll(Unknown Source) 

cố gắng để thêm một bộ sưu tập vào một danh sách

/** 
    * 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; 
    } 

Trả lời

11

Từ (tôi nhấn mạnh) javadoc of Arrays.asList():

Trả về một danh sách kích thước cố định được hỗ trợ bởi các mảng định

Nói tóm lại: bạn có thể không .add*() hoặc .remove*() từ một danh sách như vậy! Bạn sẽ phải sử dụng một danh sách có thể sửa đổi khác (ví dụ: ArrayList).

1

để giải thích một chút thực tế hơn, tôi đang sử dụng mã của bạn:

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; 
} 

Đối với mục đích của bạn, tôi sẽ làm những điều sau đây:

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

này sẽ giúp bạn có được các đối tượng Collection.

1

Arrays.asList() trả về danh sách bất biến mà bạn không thể sửa đổi.

Cụ thể hơn, phương thức add(), addAll() và remove() không được triển khai.

Các vấn đề liên quan