在 Java 中,如何定制一个不可修改的 List?请详细说明可使用的类和方法,并给出示例代码。

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ImmutableListExample {
    public static void main(String[] args) {
        // 方法1:使用Collections.unmodifiableList
        List<String> originalList = Arrays.asList("A", "B", "C");
        List<String> unmodifiableList = Collections.unmodifiableList(originalList);
        System.out.println("Unmodifiable List: " + unmodifiableList);

        // 尝试修改会抛出UnsupportedOperationException
        try {
            unmodifiableList.add("D");
        } catch (UnsupportedOperationException e) {
            System.out.println("Exception: " + e.getMessage());
        }

        // 方法2:使用Java 9的List.of
        List<String> immutableList = List.of("X", "Y", "Z");
        System.out.println("Immutable List: " + immutableList);

        // 尝试修改会抛出UnsupportedOperationException
        try {
            immutableList.add("W");
        } catch (UnsupportedOperationException e) {
            System.out.println("Exception: " + e.getMessage());
        }

        // 方法3:使用Guava的ImmutableList
        /*
         需要添加Guava依赖:
         <dependency>
             <groupId>com.google.guava</groupId>
             <artifactId>guava</artifactId>
             <version>30.1-jre</version>
         </dependency>
         */
        // ImmutableList<String> guavaImmutableList = ImmutableList.of("P", "Q", "R");
        // System.out.println("Guava Immutable List: " + guavaImmutableList);
    }
}

详细说明

在Java中,可以通过以下几种方式定制一个不可修改的List:

  1. 使用Collections.unmodifiableList

    • Collections.unmodifiableList方法接收一个普通的List,并返回一个不可修改的视图。任何试图修改此视图的操作(如添加、删除或修改元素)都会抛出UnsupportedOperationException。
    • 示例代码中展示了如何通过Collections.unmodifiableList包装一个List,以及尝试修改时的异常处理。
  2. 使用Java 9引入的List.of方法

    • Java 9引入了List.of方法,可以直接生成一个不可变的List。此方法生成的List不支持任何修改操作,包括添加、删除或替换元素。
    • 示例代码中展示了List.of的使用方式,以及尝试修改时的异常处理。
  3. 使用Guava的ImmutableList

    • Google的Guava库提供了ImmutableList类,可以生成真正的不可变List。ImmutableList的实例不会被任何方式修改,包括通过反射。
    • 由于需要额外依赖,示例代码以注释形式展示了使用方法。

注意事项

  • 使用Collections.unmodifiableList时,原始List的修改仍然会影响不可修改视图的内容。因此,建议将原始List也设为不可变。
  • List.of生成的List是完全不可变的,且性能更高,推荐在Java 9及以上版本中使用。
  • Guava的ImmutableList提供了更丰富的功能,如copyOf方法,但需要引入第三方库。

通过这些方法,可以确保List在运行时不会被意外修改,从而提高代码的安全性和稳定性。