java不能修改表,在java中不可修改的列表

该博客讨论如何在不捕获异常的情况下使列表不可修改。作者提出了一个自定义类来覆盖可能修改列表的方法,如`add`和`addAll`,返回错误并记录异常,而不是直接抛出。这种方法适用于已有的代码,不能使用`Collections.unmodifiableList`的情况。同时提醒这可能会在调试时带来困扰。
摘要由CSDN通过智能技术生成

I'm trying to set a List unmodifiable.

In my code, i have a method which returns a list.

This list should'nt be modified, but i dont want to catch the exception returned by the unmodifiableList.

private List listeReferenceSelectAll = null;

List oListeRet = new ArrayList();

oListeRet = listeReferenceSelectAll;

return new ArrayList(oListeRet);

It is an existing code and i have to transform it to return an unmodifiable list, but if an "add" method has been called, no exception has to be caught.

First i have create a class which implements List to override "add" method to log the exception and not to catch it.

But i don't know how corretly instanciate it...

If you have any other solutions,

Thanks in advance for your help :).

解决方案

If you absolutely must do this, try to follow the contract specified by java.util.List in the list you are creating.

Your code would look something like

public class UnmodifiableArrayList extends ArrayList {

public UnmodifiableArrayList(Collection extends E> c) {

super(c);

}

public boolean add(int index) {

return false;//Returning false as the element cannot be added

}

public boolean addAll(Collection extends E> c) {

return false;//Returning false as the element cannot be added

}

public E remove(int index) {

return null;//Returning null as the element cannot be removed

}

}

Add any more methods you need on the same lines. Just ensure that all the constructors and methods that might by used to modify in your code are overriden, so as to ensure the list is unmodifiable.

Using the Collections API is the cleaner and better way to do it, so use this way only if using Collections.UnmodifiableList does not satisfy your need.

And keep in mind this will be a nightmare while debugging so log as much as possible.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值