java arraylist插入,如何在Java中添加上的ArrayList监听

本文介绍如何在Java中创建一个可以监听ArrayList操作的自定义类MyList,通过重写add和remove方法实现元素变化时的动作。虽然不能直接继承ArrayList,但可以通过扩展并添加监听功能来满足需求。
摘要由CSDN通过智能技术生成

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

class UseOfMyList {

public MyList places = new MyList();

places.add("Buenos Aires");

//and to be able to do that

List cities = new ArrayList();

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?

解决方案

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{

private ArrayList 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值