有时候方法返回一个列表但是不想调用者改变列表内容。有三种方法可以实现不可变列表,通过调用JDK,Guava以及Apache Commons Collections相关API来实现。
1.JDK
@Test
public void jdkTest() {
List fruitsList = new ArrayList(Arrays.asList("Apple", "Orange"));
List fruitsUnmodifiableList = Collections.unmodifiableList(fruitsList);
fruitsUnmodifiableList.add("Pear");
}
add方法会抛出java.lang.UnsupportedOperationException异常。
2.Apache Commons Collections
@Test
public void accTest() {
List fruitsList = new ArrayList(Arrays.asList("Apple", "Orange"));
List fruitsUnmodifiableList = ListUtils.unmodifiableList(fruitsList);
fruitsUnmodifiableList.add("Pear");
}
同样的调用add方法会抛异常,源码:
public boolean add(Object object) {
throw new UnsupportedOperationException();
}
3.Guava
@Test
public void guavaTest() {
List fruitsList = new ArrayList(Arrays.asList("Apple", "Orange"));
List fruitsUnmodifiableList = ImmutableList.copyOf(fruitsList);
fruitsUnmodifiableList.add("Pear");
}
这个操作实际创建了原list的copy,不是原list的视图,Guava也提供构建器——返回强类型ImmutableList代替简单List,如下:
@Test
public void guavaTest2() {
List fruitsList = new ArrayList(Arrays.asList("Apple", "Orange"));
ImmutableList list = ImmutableList.builder().addAll(fruitsList).build();
list.add("Pear");
}