Java 使 ArrayList 只读

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2419353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:21:48  来源:igfitidea点击:

make ArrayList Read only

javacollectionsjakarta-eearraylist

提问by gmhk

In Java, how can you make an ArrayListread-only (so that no one can add elements, edit, or delete elements) after initialization?

在 Java 中,如何ArrayList在初始化后使只读(以便没有人可以添加元素、编辑或删除元素)?

采纳答案by Mark Pope

Pass the ArrayListinto Collections.unmodifiableList(). It returns an unmodifiable view of the specified list. Only use this returned List, and never the original ArrayList.

通行证ArrayList进入Collections.unmodifiableList()。它返回指定列表的不可修改视图。只使用这个返回的List,而不是原来的ArrayList

回答by Jama22

Are you sure you want to use an ArrayListin this case?

ArrayList在这种情况下,您确定要使用 an吗?

Maybe it would be better to first populate an ArrayListwith all of your information, and then convert the ArrayListinto a final array when the Java program initializes.

也许最好先ArrayList用您的所有信息填充 an ,然后ArrayList在 Java 程序初始化时将其转换为最终数组。

回答by Arunkumar Papena

Pass the list object to Collections.unmodifiableList(). See the example below.

将列表对象传递给Collections.unmodifiableList(). 请参阅下面的示例。

import java.util.*;

public class CollDemo
{
    public static void main(String[] argv) throws Exception
    {
        List stuff = Arrays.asList(new String[] { "a", "b" });
        List list = new ArrayList(stuff);
        list = Collections.unmodifiableList(list);
        Set set = new HashSet(stuff);
        set = Collections.unmodifiableSet(set);
        Map map = new HashMap();
        map = Collections.unmodifiableMap(map);
        System.out.println("Collection is read-only now.");
    }
}

回答by Amar Magar

Pass the collection object to its equivalent unmodifiable function of Collectionsclass. The following code shows use of unmodifiableList

将集合对象传递给Collections类的等效不可修改函数。以下代码显示了使用unmodifiableList

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class Temp {

    public static void main(String[] args) {

        List<Integer> objList = new ArrayList<Integer>();
        objList.add(4);
        objList.add(5);
        objList.add(6);
        objList.add(7);

        objList = Collections.unmodifiableList(objList);
        System.out.println("List contents " + objList);

        try {
            objList.add(9);
        } catch(UnsupportedOperationException e) {
            e.printStackTrace();
            System.out.println("Exception occured");
        }
        System.out.println("List contents " + objList);
    }

}

same way you can create other collections unmodifiable as well

同样,您也可以创建其他不可修改的集合