Issue
What method should I use in the setter of a JavaFX ObservableSet
collection to clear the set and initialise it to the given collection? ObservableList
has the method setAll(Collection)
that is used to initialise the list by first clearing it.
The closest I have seen is addAll(Collection)
which does not clear the set beforehand. When setting the collection in my project I want it to have the normal behaviour of setting the ObservableSet
to a new set, but according to the javadoc:
Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the specified collection is also a set, the
addAll
operation effectively modifies this set so that its value is the union of the two sets.
I cannot just set the value using =
because the passed parameter in the setter is a set and the ObservableSet
is an internal wrapper that the outside knows nothing about. I also would like to avoid doing clear
then addAll
.
Solution
As you can see in the Javadoc of ObservableSet
, there is no such method.
In fact, the method ObservableList::setAll
is just a convenient "shortcut":
Clears the ObservableList and add all elements from the collection.
The common implementation ModifiableObservableListBase
in JavaFX does a clear
then an addAll
:
@Override
public boolean setAll(Collection<? extends E> col) {
beginChange();
try {
clear();
addAll(col);
} finally {
endChange();
}
return true;
}
The main advantage of having a setAll
shortcut is that only one "big" change event (ListChangeListener.Change
) is sent to the listeners. Better performance.
In fact, you might want to extend com.sun.javafx.collections.ObservableSetWrapper
with your own setAll
but there will be no performance benefit since the event SetChangeListener.Change
is an elementary change: m
removed events, and n
added events will be sent.
So you have no other choice than:
set.clear();
set.addAll(otherSet);
or copy in a new set and assign:
set = FXCollections.observableSet(otherSet);
Answered By - gontard
Answer Checked By - Cary Denson (JavaFixing Admin)