在java中不可修改的列表 [英] Unmodifiable List in java

查看:323
本文介绍了在java中不可修改的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个List不可修改。

I'm trying to set a List unmodifiable.

在我的code,我有它返回一个列表的方法。

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

这个名单should'nt进行修改,但我不想搭上了返回unmodifiableList例外。

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

private List<T> listeReferenceSelectAll = null;
List<T> oListeRet = new ArrayList<T>();
oListeRet = listeReferenceSelectAll;
return new ArrayList<T>(oListeRet);

这是现有code和我有改造它返回一个不可修改的列表,但如果增加方法被调用,也不例外已被抓获。

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.

但我不知道该怎么corretly实例化它...

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

如果您有任何其他的解决方案,
在此先感谢您的帮助。)

If you have any other solutions, Thanks in advance for your help :).

推荐答案

如果你绝对必须这样做,尽量遵循的的java.util.List 的列表中,你正在创建指定的合同。

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

您code看起来像

public class UnmodifiableArrayList<E>  extends ArrayList<E> {

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

添加任何你需要在同一行更多的方法。刚确保可能由使用在code修改所有构造函数和方法重写,以确保该列表是不可修改的。

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.

使用集合API是更清洁和更好的方式来做到这一点,所以只能使用,如果使用Collections.UnmodifiableList不能满足您的需要这种方式。

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.

这篇关于在java中不可修改的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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