gpt4 book ai didi

java - ObservableList 中 setAll() 方法的 ObservableSet 等价物是什么

转载 作者:搜寻专家 更新时间:2023-11-01 02:44:58 25 4
gpt4 key购买 nike

我应该在 JavaFX ObservableSet 集合的 setter 中使用什么方法来清除集合并将其初始化为给定集合? ObservableList 具有方法 setAll(Collection) 用于通过首先清除列表来初始化列表。

我见过的最接近的是 addAll(Collection),它没有预先清除集合。在我的项目中设置集合时,我希望它具有将 ObservableSet 设置为新集合的正常行为,但根据 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.

我不能只使用 = 设置值,因为 setter 中传递的参数是一个集合,而 ObservableSet 是外部一无所知的内部包装器。我还想避免执行 clear 然后 addAll

最佳答案

正如您在 ObservableSet 的 Javadoc 中看到的,没有这样的方法。

其实ObservableList::setAll这个方法只是一个方便的“捷径”:

Clears the ObservableList and add all elements from the collection.

JavaFX 中的常见实现 ModifiableObservableListBase 执行一个clear 然后一个 addAll:

@Override
public boolean setAll(Collection<? extends E> col) {
beginChange();
try {
clear();
addAll(col);
} finally {
endChange();
}
return true;
}

setAll 快捷方式的主要优点是只向监听器发送一个“大”change event (ListChangeListener.Change)。更好的性能。

事实上,您可能想用自己的 setAll 扩展 com.sun.javafx.collections.ObservableSetWrapper,但不会有任何性能优势,因为事件 SetChangeListener.Change基本更改:删除了 m 个事件,将发送 n 个添加的事件。

所以你别无选择,只能:

set.clear();
set.addAll(otherSet);

或复制到新的集合中并分配:

set = FXCollections.observableSet(otherSet);

关于java - ObservableList 中 setAll() 方法的 ObservableSet 等价物是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24799125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com