使 ArrayList 只读
在 Java 中,如何在初始化后将 ArrayList 设为只读(这样就没有人可以添加元素、编辑或删除元素)?
In Java, how can you make an ArrayList
read-only (so that no one can add elements, edit, or delete elements) after initialization?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将
ArrayList
传递到Collections.unmodifyingList()
。它返回指定列表的不可修改视图。仅使用此返回的List
,而不是原始的ArrayList
。Pass the
ArrayList
intoCollections.unmodifiableList()
. It returns an unmodifiable view of the specified list. Only use this returnedList
, and never the originalArrayList
.将列表对象传递给
Collections.unmodifyingList()
。请参阅下面的示例。Pass the list object to
Collections.unmodifiableList()
. See the example below.将集合对象传递给
集合
类。以下代码显示了unmodifyingList
同样,您也可以创建其他不可修改的集合
Collections.unmodifyingMap(map)
Collections.unmodifyingSet(set)
< /a>Pass the collection object to its equivalent unmodifiable function of
Collections
class. The following code shows use ofunmodifiableList
same way you can create other collections unmodifiable as well
Collections.unmodifiableMap(map)
Collections.unmodifiableSet(set)
您确定要在这种情况下使用 ArrayList 吗?
也许最好先用所有信息填充 ArrayList,然后在 Java 程序初始化时将 ArrayList 转换为最终数组。
Are you sure you want to use an
ArrayList
in this case?Maybe it would be better to first populate an
ArrayList
with all of your information, and then convert theArrayList
into a final array when the Java program initializes.您可以使用它作为初始化有序不可变列表的便捷方法。
注意:虽然其他答案也有效并回答了这个问题,但我觉得这个花絮为整个对话增加了价值。
You can use this as a convenient way to initialize your ordered immutable List.
Note: Though other answers also work and answer the question, I feel like this tidbit adds value to the overall conversation.