无法将 java.util.Collections$EmptySet 转换为 java.util.HashSet

Cannot cast java.util.Collections$EmptySet to java.util.HashSet

我正在使用 Vaadin14 和 Java 1.8。我想实现一个多 select 组合框,这就是我使用以下 Vaadin 插件的原因:https://vaadin.com/directory/component/multiselect-combo-box/api/org/vaadin/gatanaso/MultiselectComboBox.html

实例化和使用组合框效果很好,但出现错误

java.lang.RuntimeException: java.lang.ClassCastException: Cannot cast java.util.Collections$EmptySet to java.util.HashSet

尝试 "save" 组合框中没有任何项目的对象时 select。如果我至少有一个项目 selected,它工作正常,但是一旦 selection 为空并且我尝试保存对象 ("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<> 尝试了它,但最终成功的方法是向上进行另一个抽象级别,并在中使用 Collection<> 而不是 HashSet<> class 定义 (Oracle Docs)。

public class AnotherClass  implements Serializable {

     @NotNull
     private int id = -1;

     private Collection<MyClass> myHashSet= new HashSet<MyClass>();

}