瓦丁不能铸造java。util。集合$EmptySet到java。util。哈希集
我使用的是Vaadin14和Java1.8。我想实现一个多选组合框,这就是我使用以下Vaadin插件的原因: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
尝试“保存”组合框中未选择任何项目的对象时。如果我至少选择了一个项目,它工作正常,但一旦选择为空并且我尝试保存对象(“另一个类”),我就会收到错误
// 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是以下类中的一个属性:
public class AnotherClass implements Serializable {
@NotNull
private int id = -1;
private HashSet<MyClass> myHashSet= new HashSet<MyClass>();
}
当我创建另一个类的实例时,我总是使用myHashSet属性的空HashSet而不是null来实例化它们
如何修复上述错误
# 1 楼答案
在尝试了@Rogue在评论中给我的提示后,我用Set<>;首先,但最终的诀窍是向上提升另一个抽象层次,并使用集合<>;而不是HashSet<>;在类定义(Oracle Docs)中