簡體   English   中英

HashSet 拋出 UnsupportedOperationException

[英]HashSet throws UnsupportedOperationException

我有以下代碼,當我使用removeremoveIf從 Set 中刪除一個項目時,出現錯誤java.lang.UnsupportedOperationException: null

private Set<Speciality> specialities = new HashSet<>();

private void updateSpeciality(SpecialityETAUpdatedEvent evt) {
    if (CollectionUtils.isNotEmpty(this.specialities)) {
        Optional<Speciality> specialityOptional = this.specialities.stream().filter((Speciality speciality) -> speciality.getCode().equals(evt.code)).findFirst();
        if (specialityOptional.isPresent()) {
            this.specialities.remove(specialityOptional.get());// **** Exception thrown here
        }
    }
    this.specialities.add(new Speciality().code(evt.code).label(evt.label).startDate(evt.startDate));
}

java.lang.UnsupportedOperationException: null at java.util.Collections$UnmodifiableCollection.remove(Collections.java:1060) at com.xxxx.updateSpeciality(EstablishmentAggregate.java:916) at com.xxxx.EstablishmentAggregate.on(EstablishmentAggregate.java: 909) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect .Method.invoke(Method.java:498)

你確定 specialities 是HashSet嗎? 可以在某處創建為不同的類型嗎? 例如,可以在不可修改的集合上拋出UnsupportedOperationException

似乎在某處您可以使用顯式setSpecialities設置specialities ,並傳遞一個 object ,它是一個Set ,但不是一個HashSet

在這種情況下,實例化 Set 的類不支持removeremoveIf方法,它們的實現類似於以下代碼:

public boolean remove(Object o) {
   throw new UnsupportedOperationException();
}

創建不可修改 Set 的一種方法是例如使用 java 9 Set.of 的Set.of

返回包含零個元素的不可變集合

正如javadoc中所解釋的:

Set.of() static 工廠方法提供了一種創建不可變集合的便捷方式。 這些方法創建的 Set 實例具有以下特點:

  • 它們在結構上是不可變的。 不能添加或刪除元素。 調用任何 mutator 方法總是會導致 UnsupportedOperationException 被拋出 但是,如果包含的元素本身是可變的,這可能會導致 Set 行為不一致或其內容似乎發生變化。

以下是我將如何更新或添加集合中的條目。

import java.util.*;
class Record {
    int id, val;
    Record(int id) { this.id = id; }
    Record(int id, int val) { this.id = id; this.val=val;}
  
    public boolean equals(Object o){
        return o instanceof Record ? id==((Record)o).id : false;
    }
    public int hashCode() {  
        return Objects.hashCode(id);
    }
    public String toString(){
        return String.format("Container[id=%d, val=%d]", id, val);
    }
}

class RecordSet extends HashSet<Record> {
    Record addOrUpdate(Record c){
        remove(c);
        add(c);
        return c;
    }
}

public class Main {
    public static void main(String[] args) {
        RecordSet set = new RecordSet();
        set.add(new Record(1,100));
        set.add(new Record(2,200));
        set.add(new Record(3,300));
        
        System.out.println("Before: " + set);
        
        Record c1 = new Record(1,500);  //update existing record
        Record c2 = new Record(4,400);  //new record
        
        set.addOrUpdate(c1);
        set.addOrUpdate(c2);
        
        System.out.println("After: " + set);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM