Search code examples
javajava-11observablelistjavafx-11

How can I cast an ObservableList to an ObservableSet


I'm migrating an application from Java 1.7 to Java 11 which uses JavaFX.

During the migration I met a cast probleme where I have an ObservableList and I need an ObservableSet.

I tried to cast with (ObservableSet<MyObject>) MyObservableList<MyObject> but I have :

ERROR; UNCOUGHT Exception java.lang.ClassCastException: class com.sun.javafx.collections.ObservableListWrapper cannot be cast to class javafx.collections.ObservableSet (com.sun.javafx.collections.ObservableListWrapper and javafx.collections.ObservableSet are in module javafx.base of loader 'app') java.lang.ClassCastException: class com.sun.javafx.collections.ObservableListWrapper cannot be cast to class javafx.collections.ObservableSet (com.sun.javafx.collections.ObservableListWrapper and javafx.collections.ObservableSet are in module javafx.base of loader 'app')

Do you have an idea to cast/transform this Object properly ? Thank you for your answer !


Solution

  • You cannot cast it, the internal representation is different. You can initialize a new ObservableSet object and addAll your list, which takes any kind of collection.