如何在java中的ArrayList上添加监听器 [英] How to add listener on ArrayList in java

查看:70
本文介绍了如何在java中的ArrayList上添加监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 java 中创建我自己的 ArrayList 实现,它可以在列表更改时进行侦听,并在发生这种情况时执行操作.从我读过的内容来看,我明白我不能扩展 ArrayList 然后添加侦听器.

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.

我想在类中使用MyList作为带有public修饰符的变量,这样用户就可以直接修改它,并在他修改的时候完成action.

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;

那么如何创建以及何时添加、删除或传递另一个列表到 MyList 一个要执行的操作?

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

推荐答案

你不能通过扩展 ArrayList 来做到这一点,因为它没有内置的通知机制(和,此外,因为它已被声明为 final ,因此无法扩展).但是,您可以通过创建自己的 List 实现并添加与 add()remove()<相比的侦听器"功能来实现所需的结果/code> 方法:

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

这篇关于如何在java中的ArrayList上添加监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆