使 ArrayList 只读

发布于 2024-08-25 00:48:55 字数 62 浏览 5 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

小伙你站住 2024-09-01 00:48:55

ArrayList 传递到 Collections.unmodifyingList()。它返回指定列表的不可修改视图。仅使用此返回的 List,而不是原始的 ArrayList

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.

默嘫て 2024-09-01 00:48:55

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

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.");
    }
}

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

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.");
    }
}
久隐师 2024-09-01 00:48:55

将集合对象传递给 集合类。以下代码显示了 unmodifyingList

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

}

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

Pass the collection object to its equivalent unmodifiable function of Collections class. The following code shows use of 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

酷炫老祖宗 2024-09-01 00:48:55

您确定要在这种情况下使用 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 the ArrayList into a final array when the Java program initializes.

吐个泡泡 2024-09-01 00:48:55

您可以使用它作为初始化有序不可变列表的便捷方法。

List<Integer> unmodifiableList = List.of(1,2,3,4,5);

不可修改的列表 来源

List.of 和 List.copyOf 静态工厂方法提供了
创建不可修改列表的便捷方法。列表实例
这些方法创建的具有以下特点:

  • 它们是不可修改的。无法添加、删除或替换元素。调用 List 上的任何 mutator 方法总是会导致
    抛出 UnsupportedOperationException。然而,如果包含
    元素本身是可变的,这可能会导致列表的内容
    似乎发生了变化。
  • 它们不允许空元素。尝试使用 null 元素创建它们会导致 NullPointerException。
  • 如果所有元素都是可序列化的,那么它们就是可序列化的。
  • 列表中元素的顺序与提供的参数或提供的数组中元素的顺序相同。
  • 列表及其子列表视图实现 RandomAccess 接口。
  • 它们以价值为基础。程序员应该将相等的实例视为可互换的,并且不应该将它们用于同步,
    或可能发生不可预测的行为。例如,在未来的版本中,
    同步可能会失败。调用者不应做出任何假设
    返回实例的身份。工厂可以自由创造新的
    实例或重用现有实例。
  • 它们按照序列化表单页面上的指定进行序列化。

注意:虽然其他答案也有效并回答了这个问题,但我觉得这个花絮为整个对话增加了价值。

You can use this as a convenient way to initialize your ordered immutable List.

List<Integer> unmodifiableList = List.of(1,2,3,4,5);

Unmodifiable Lists Source

The List.of and List.copyOf static factory methods provide a
convenient way to create unmodifiable lists. The List instances
created by these methods have the following characteristics:

  • They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause
    UnsupportedOperationException to be thrown. However, if the contained
    elements are themselves mutable, this may cause the List's contents to
    appear to change.
  • They disallow null elements. Attempts to create them with null elements result in NullPointerException.
  • They are serializable if all elements are serializable.
  • The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
  • The lists and their subList views implement the RandomAccess interface.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization,
    or unpredictable behavior may occur. For example, in a future release,
    synchronization may fail. Callers should make no assumptions about the
    identity of the returned instances. Factories are free to create new
    instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

Note: Though other answers also work and answer the question, I feel like this tidbit adds value to the overall conversation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文