您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何将可观察集转换为可观察列表

如何将可观察集转换为可观察列表

不,因为,您正在复制集合:

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
    }
}
其他 2022/1/1 18:27:27 有504人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶