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