温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中如何实现不可变集合

发布时间:2025-09-19 03:59:46 来源:亿速云 阅读:100 作者:小樊 栏目:编程语言

在Java中,要创建一个不可变集合,可以使用Collections.unmodifiableXXX()方法,这些方法接收一个可变集合作为参数,并返回一个不可变的视图。以下是一些示例:

  1. 不可变列表(Immutable List):
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ImmutableListExample {
    public static void main(String[] args) {
        List<String> mutableList = new ArrayList<>();
        mutableList.add("One");
        mutableList.add("Two");
        mutableList.add("Three");

        List<String> immutableList = Collections.unmodifiableList(mutableList);

        // 尝试修改不可变列表将抛出UnsupportedOperationException
        // immutableList.add("Four");
    }
}
  1. 不可变集合(Immutable Set):
import java.util.HashSet;
import java.util.Collections;
import java.util.Set;

public class ImmutableSetExample {
    public static void main(String[] args) {
        Set<String> mutableSet = new HashSet<>();
        mutableSet.add("One");
        mutableSet.add("Two");
        mutableSet.add("Three");

        Set<String> immutableSet = Collections.unmodifiableSet(mutableSet);

        // 尝试修改不可变集合将抛出UnsupportedOperationException
        // immutableSet.add("Four");
    }
}
  1. 不可变映射(Immutable Map):
import java.util.HashMap;
import java.util.Collections;
import java.util.Map;

public class ImmutableMapExample {
    public static void main(String[] args) {
        Map<String, Integer> mutableMap = new HashMap<>();
        mutableMap.put("One", 1);
        mutableMap.put("Two", 2);
        mutableMap.put("Three", 3);

        Map<String, Integer> immutableMap = Collections.unmodifiableMap(mutableMap);

        // 尝试修改不可变映射将抛出UnsupportedOperationException
        // immutableMap.put("Four", 4);
    }
}

请注意,这些方法返回的不可变集合实际上是原始可变集合的视图。因此,如果原始可变集合在创建不可变视图后被修改,那么不可变视图也会反映出这些更改。为了避免这种情况,可以在创建不可变视图之前确保原始可变集合已经完成初始化。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI