java中不可变ArrayList
本文简要说明如果使ArrayList不可变,通过jdk,Guava以及Apache Commons Collections方式实现。
使用JDK
首先,jdk提供了漂亮的方式从已经存在的集合中获得不可修改的集合:
Collections.unmodifiableList(list);
返回新的集合不能被修改:
@Test(expected = UnsupportedOperationException.class)
public void givenUsingTheJdk_whenUnmodifiableListIsCreated_thenNotModifiable() {
List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
List<String> unmodifiableList = Collections.unmodifiableList(list);
unmodifiableList.add("four");
}
使用Guava
Guava提供类似功能,创建了ImmutableList来实现:
ImmutableList.copyOf(list);
类似情况,返回结果不能修改:
@Test(expected = UnsupportedOperationException.class)
public void givenUsingGuava_whenUnmodifiableListIsCreated_thenNotModifiable() {
List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
List<String> unmodifiableList = ImmutableList.copyOf(list);
unmodifiableList.add("four");
}
注意,这个操作实际创建了原list的copy,不是原list的视图。Guava也提供构建器——返回强类型ImmutableList代替简单List。
@Test(expected = UnsupportedOperationException.class)
public void givenUsingGuavaBuilder_whenUnmodifiableListIsCreated_thenNoLongerModifiable() {
List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
ImmutableList<Object> unmodifiableList = ImmutableList.builder().addAll(list).build();
unmodifiableList.add("four");
}
使用Apache Commons Collections
最后,Apache Commons Collections 也提供了API创建不可修改list:
ListUtils.unmodifiableList(list);
同样,如果修改则抛出UnsupportedOperationException异常:
@Test(expected = UnsupportedOperationException.class)
public void givenUsingCommonsCollections_whenUnmodifiableListIsCreated_thenNotModifiable() {
List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
List<String> unmodifiableList = ListUtils.unmodifiableList(list);
unmodifiableList.add("four");
}
总结
我们描述了如何轻松基于已经存在的ArrayList创建不可修改list,基于三种方式实现,希望对你有帮助。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/79782674