0

I created a List which is to be observed for changes which is triggered by console input by user,suppose a user enters a string then that string should be subscribed in the observed list.

Himanshu Ranjan
  • 282
  • 1
  • 7
  • 22

1 Answers1

0

You should create a customList like this :

public class CustomList<T> extends ArrayList<T> {
    public static void main(String[] args) {
        CustomList<String> customList = new CustomList<>();
        customList.add("First Adding");
    }
    public boolean add(T t) {
        boolean b = super.add(t);
        System.out.println("you just add :" + t.toString());
        return b;
    }
}

If you want to have a lot of custom event you can do this :

public class CustomList<T> extends ArrayList<T> {
    public static void main(String[] args) {
        CustomList<String> customList = new CustomList<>(new EventCustomList<String>() {
            public void remove(String s) {
                System.out.println("you just remove :" + s);
            }
            public void add(String s) {
                System.out.println("you just add :" + s);
            }
        });
        customList.add("First Adding");
    }
    private EventCustomList event;
    public CustomList (EventCustomList<T> event) {
        this.event = event;
    }
    public boolean add(T t) {
        boolean b = super.add(t);
        event.add(t);
        return b;
    }
    public T remove(int index) {
        T t = super.remove(index);
        remove(index);
        return t;
    }
    public interface EventCustomList<T> {
        void add(T t);
        void remove(T t);
    }
}

Or you can use BackedList like this topic How to add listener on ArrayList in java

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");});
            }
        }
    });
mehdim2
  • 129
  • 9