如何在Java中添加上的ArrayList监听(How to add listener on Arr

2019-09-02 23:42发布

我想在Java中创建我自己的实现的ArrayList,它可以侦听当列表正在发生变化,并做动作时出现这种情况。 从我已阅读,我明白,我不能延伸的ArrayList,然后添加监听器。

我想用MYLIST在课堂上与公众修饰的变量,这样用户就可以直接更改它,当他改变它做的动作。

class MyList extends ArrayList<object>.... {  ... }
 class UseOfMyList {
 public MyList places = new MyList<Object>();
 places.add("Buenos Aires");
 //and to be able to do that
 List cities = new ArrayList<Object>();
 cities.add("Belmopan");
 places = cities;

那么如何创建并添加做的时候,移除或通过另一个列表MYLIST一个要执行的操作?

Answer 1:

你不是要能够通过扩展来做到这一点ArrayList ,因为它没有内置的通知机制(以及进一步的,因为它已经被宣布final ,因此不能扩展)。 但是,您可以通过创建自己的实现你想要的结果List的实施和增加你的“监听”功能相一相的add()remove()方法:

class MyList<T>{
    private ArrayList<T> list;

    public MyList(){
        list = new ArrayList<>();
        ...
    }
    public void add(T t){
        list.add(t) 
        //do other things you want to do when items are added 
    }
    public T remove(T t){
        list.remove(t);
        //do other things you want to do when items are removed
    }
}


Answer 2:

存入RESP账户。 ;)

private class MyList extends ArrayList<Objects> {

      @Override
      public void sort(Comparator c) {
        super.sort(c); 
        resetLancamentos(); // call some metod ;)
      }
    //...
     @Override
     public boolean removeAll(Collection c) {
        //To change body of generated methods, choose Tools | Templates.
        boolean ret = super.removeAll(c);
        resetLancamentos(); // some metod like fireObjChanged() will do the job too
         return ret;
     }

}


Answer 3:

老问题,我知道了。 我提前道歉的任何不良格式或代码丢失行。 我是一个长期用户,第一次贡献者。

总之,因为去除的JavaFX从JDK11的,我不得不写我自己的ObservableList的版本。 当然,我们可以与JMods或Maven噗通JavaFX的,但它似乎有点像只为FXCollections矫枉过正。

长篇短发......呃:)

我开始阅读这个老问题,答案并不完全适合我的需要,所以我添加了一个自定义事件/监听器类。

想我可以分享,因为这个网站已经改善了我的编码10倍。

public static void main(String[] args) {        
    BackedList<String> list = new BackedList();
    list.addListener(new BackedListListener<String>(){
        @Override
        public void setOnChanged(ListChangeEvent<String> event) {
            if (event.wasAdded()) {
                event.getChangeList().forEach(e->{
                   // do whatever you need to do                        
                    System.out.println("added: " + e);
                });
            }
            if (event.wasRemoved()) {

                // do whatever you need to dl
                event.getChangeList().forEach(e->{System.out.println(e + " was removed");});
            }
        }
    });

类别:BackedObservableList

    public class BackedObservableList<T> implements List<T> {
        private final List<T> backed;

    public BackedObservableList() {
        backed = new ArrayList();
    }

    public BackedObservableList(List<T> backed) {
        this.backed = backed;
    }

        /*

        You will want to override every method. For any method that performs an add/remove 
        operation, you will have to do some coding / testing. I'll do an add() op, a remove() 
        op, and an interator in this example. Anything that is not an add/remove op, you can straight up delegate it to the underlying list. 
Also remember that list.clear() is a removal operation, where you can simply iterate through the backed list and call the overide remove(T t) method, or just plop the whole backed list into the ListChangeEvent<T> class and delegate to the backed array again.


                */


     @Override
        public boolean add(T e) {
            if (backed.add(e)) {
                ListChangeEvent<T> event = new ListChangeEvent(this, backed.indexOf(e), backed.indexOf(e) + 1, true, e);
                    notifyListeners(event);
                return true;
                }
            return false;
                }

        }

    @Override
    public boolean remove(Object o) {
        if (backed.remove(o)) {
            ListChangeEvent<T> event = new ListChangeEvent(this, backed.indexOf(o), 

    backed.indexOf(o) + 1, false, o);
                notifyListeners(event);
                return true;
            }
            return false;
        }
    /*

    The iterator seemed easy enough, until I remembered the iterator.remove() call. 
    I still haven't fully tested it (it works, but only as far as I've used it)

    */
     @Override
        public Iterator<T> iterator() {        
            return new Iterator<T>() {
                T currentItem = null;
                int currentIndex = 0;

            @Override
            public boolean hasNext() {
                return backed.size() > currentIndex;
            }

            @Override
            public T next() {

                return currentItem = backed.get(currentIndex++);
            }

            @Override
            public void remove() {
                if (backed.remove(currentItem)) {
                    currentIndex--;
                    notifyListeners(new ListChangeEvent<T>(backed, currentIndex, currentIndex + 1, false, currentItem));
                }
            }
        };
    }


     private void notifyListeners(ListChangeEvent<T> event) {
            for (BackedListListener<T> listener : listeners) {
                listener.setOnChanged(event);
            }
        }

        private final List<BackedListListener> listeners = new ArrayList();

        public void addListener(BackedListListener<T> listener) {
            listeners.add(listener);
        }

类别:ListChangeEvent

它只是提供给支持列表(您可能需要使用Collections.unmodifiableList包装一个参考()

public class ListChangeEvent<T> {
private final List<T> source;
private final List<T> changeList;
private final boolean wasAdded;    
private final int to, from;

public ListChangeEvent(List<T> source, int from, int to, boolean wasAdded, T... changeItems) {
    this(source, from, to, wasAdded, Arrays.asList(changeItems));
}


    public ListChangeEvent(List<T> source, int from, int to, boolean wasAdded, List<T> changeItems) {
        this.source = source;
        this.changeList = changeItems;
        this.wasAdded = wasAdded;
        this.to = to;
        this.from = from;                
    }

    public int getFrom() {
        return from;
    }

    public int getTo() {
        return to;
    }

    public List<T> getSource() {
        return source;
    }

    public List<T> getChangeList() {
        return changeList;
    }

    public boolean wasAdded() {
        return wasAdded;
    }

    public boolean wasRemoved() {
        return !wasAdded;
    }            
}

类别:BackedListListener

    /*
    Finally a little functional interface... or, because I was too lazy to change it to one, a simple one-liner abstract class with some generics
    */
    public abstract class BackedListListener<T> {

    public abstract void setOnChanged(ListChangeEvent<T> event);        

}


文章来源: How to add listener on ArrayList in java