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

查看:5407
本文介绍了如何在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类与公开修饰的变量,因此用户可以直接更改它,当他改变它做的动作。

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 ,因为它没有内置-in通知机制(以及进一步的,因为它已经被宣布最后,因此不能扩展)。但是,您可以通过创建自己的列表的实施和增加你的监听功能相一相的添加()删除()方法:

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天全站免登陆