![](/img/trans.png)
[英]java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.HashSet
[英]Cannot cast java.util.Collections$EmptySet to java.util.HashSet
我正在使用 Vaadin14 和 Java 1.8。 I want to implement a multi-select combobox, which is why I am using the following Vaadin addon: https://vaadin.com/directory/component/multiselect-combo-box/api/org/vaadin/gatanaso/MultiselectComboBox.html
实例化和使用 combobox 效果很好,但我得到了错误
java.lang.RuntimeException: java.lang.ClassCastException: Cannot cast java.util.Collections$EmptySet to java.util.HashSet
当试图“保存”一个 object 时没有在 combobox 中选择任何项目。 如果我至少选择了一项,它可以正常工作,但是一旦选择为空并且我尝试保存 object(“AnotherClass”),我就会收到错误消息。
// creating a combobox
private MultiselectComboBox<MyClass> multiselectComboBox;
multiselectComboBox= new MultiselectComboBox<>();
// setting items to choose from
final MyClassDataProvider dataProvider = new MyClassDataProvider();
List<MyClass> allAvailableOptions = new ArrayList<>(dataProvider.getItems());
multiselectComboBox.setItems(allAvailableOptions);
multiselectComboBox.setItemLabelGenerator(MyClass::getName); // display name only
// binding the combobox to a field of AnotherClass
binder = new BeanValidationBinder<>(AnotherClass.class);
binder.forField(multiselectComboBox)
.bind("myHashSet");
// save-button
save = new Button("Save");
save.addClickListener(event -> {
if (currentObject!= null
&& binder.writeBeanIfValid(currentObject)) { // error in this line
viewLogic.saveRisk(currentObject);
}
});
HashSet 是以下 class 中的一个属性:
public class AnotherClass implements Serializable {
@NotNull
private int id = -1;
private HashSet<MyClass> myHashSet= new HashSet<MyClass>();
}
当我创建 AnotherClass 的实例时,我总是不使用 null 而是使用属性 myHashSet 的空 HashSet 来实例化它们。
如何解决上述错误?
在尝试了@Rogue 在评论中给我的提示后,我首先使用 Set<> 进行了尝试,但最终的诀窍是向上进行另一个抽象级别并在 class 定义中使用 Collection<> 而不是 HashSet<> ( Oracle文档)。
public class AnotherClass implements Serializable {
@NotNull
private int id = -1;
private Collection<MyClass> myHashSet= new HashSet<MyClass>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.