总结
JDK中的unmodifiableList的构造函数是对原始集合的浅拷贝,
而Guava.ImmutableList.copyOf是对原始集合的深拷贝
public class ImmutableDemo { public static void main(String[] args) { List<String> originalList = new ArrayList<>(); originalList.add("a"); originalList.add("b"); originalList.add("c"); List<String> jdkUnmodifiableList = Collections.unmodifiableList(originalList); List<String> guavaImmutableList = ImmutableList.copyOf(originalList); //jdkUnmodifiableList.add("d"); // 抛出UnsupportedOperationException // guavaImmutableList.add("d"); // 抛出UnsupportedOperationException originalList.add("d"); print(originalList); // a b c d print(jdkUnmodifiableList); // a b c d 对原始list的修改,会影响java 不变集合类的结果 print(guavaImmutableList); // a b c } private static void print(List<String> list) { for (String s : list) { System.out.print(s + " "); } System.out.println(); } }
标签:print,List,originalList,add,集合,jdkUnmodifiableList,设计模式,不变 From: https://www.cnblogs.com/frankcui/p/17824486.html