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
make ArrayList Read only
提问by gmhk
In Java, how can you make an ArrayList
read-only (so that no one can add elements, edit, or delete elements) after initialization?
在 Java 中,如何ArrayList
在初始化后使只读(以便没有人可以添加元素、编辑或删除元素)?
采纳答案by Mark Pope
Pass the ArrayList
into 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 ArrayList
in this case?
ArrayList
在这种情况下,您确定要使用 an吗?
Maybe it would be better to first populate an ArrayList
with all of your information, and then convert the ArrayList
into 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 Collections
class. 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
同样,您也可以创建其他不可修改的集合