【发布时间】:2022-01-22 23:14:46
【问题描述】:
我有下面的代码,当我使用remove 或removeIf 从集合中删除一个项目时,得到一个错误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) 在 com.xxxx.updateSpeciality(EstablishmentAggregate.java:916) 在 com.xxxx.EstablishmentAggregate.on(EstablishmentAggregate.java:909) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method.java:498)
【问题讨论】:
-
请参阅minimal reproducible example。您需要使您的代码示例成为我们可以复制/粘贴、运行和观察与您相同的结果;否则我们无法找出导致问题的原因。
-
您需要提供堆栈跟踪。
-
解释在你的调用栈中:你的集合是
UnmodifiableCollection;不是HashSet。你给specialities分配了什么? -
我想知道堆栈跟踪中的“UnmodifiableCollection”...这可能与在发布的代码中创建的
Set不同 - 包含 minimal reproducible example 的一个原因(例如,Set.of(...)返回这样一个不可修改的集合)