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

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

问题描述

我正在尝试将 List 设置为不可修改.

I'm trying to set a List unmodifiable.

在我的代码中,我有一个返回列表的方法.

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

这个列表不应该被修改,但我不想捕捉 unmodifiableList 返回的异常.

This list shouldn't be modified, but I don't 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);

这是一个现有代码,我必须将其转换为返回一个不可修改的列表,但如果调用了add"方法,则不必捕获异常.

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.

首先,我创建了一个实现 List 的类来覆盖add"方法来记录异常而不是捕获它.

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 to correctly instantiate it...

推荐答案

如果您绝对必须这样做,请尝试遵循您正在创建的列表中 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.

你的代码看起来像

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

在同一行添加您需要的更多方法.只需确保在您的代码中可能用于修改的所有构造函数和方法都被覆盖,以确保列表不可修改.

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.

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