Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
906 views
in Technique[技术] by (71.8m points)

list - How to add listener on ArrayList in java

I want to create my own implementation of ArrayList in java, that can listen when the list is changing and to do action when this happens. From what I have read, I understand that I can't extend ArrayList and then add listener.

I want to use MyList in class as a variable with public modifier, so users can change it directly and to be done action when he changes it.

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;

So how to create and when do add,remove or pass another list to MyList an action to be performed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're not going to be able to do this by extending ArrayList, as it has no built-in notification mechanism (and, further, because it is has been declared final and thus cannot be extended). However, you can achieve your desired result by creating your own List implementation and adding your "listener" functionality vis a vis the add() and remove() methods:

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...