不,因为,您正在复制集合:
new ArrayList<E>(pojo.getObservableSet())
我认为正确的方法是不这样做。Set
不是List
,反之亦然。两者都有特定的矛盾。例如,列表是有序的,并且集合不包含重复的元素。
而且,也FXCollections
都没有Bindings
提供这种东西。
我想您可以编写一个customObservableList
,例如Parent::children
具有类似的行为。IllegalArgumentException
如果添加了重复的子项,则抛出。如果您查看源代码,将会看到它是一个VetoableListDecorator
扩展。您可以编写自己的:
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import com.sun.javafx.collections.VetoableListDecorator;
public class CustomObservableList<E> extends VetoableListDecorator<E> {
public CustomObservableList(ObservableList<E> decorated) {
super(decorated);
}
@Override
protected void onProposedChange(List<E> toBeAdded, int... indexes) {
for (E e : toBeAdded) {
if (contains(e)) {
throw new IllegalArgumentException("Duplicament element added");
}
}
}
}
class Test {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
Set<Object> set = new HashSet<Object>();
set.add(o1);
CustomObservableList<Object> list = new CustomObservableList<Object>(FXCollections.observableArrayList(set));
list.add(o2);
list.add(o1); // throw Exception
}
}