Collections. unmodifiableCollection(Collection c) 上代码 感兴趣的可以复制试试
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1");
Collection<String> listC = Collections.unmodifiableCollection(list);
listC.add("2");
}
}
看下源码 注释写的很明白 只读集合
/**
* Returns an unmodifiable view of the specified collection. This method
* allows modules to provide users with "read-only" access to internal
* collections. Query operations on the returned collection "read through"
* to the specified collection, and attempts to modify the returned
* collection, whether direct or via its iterator, result in an
* <tt>UnsupportedOperationException</tt>.<p>
*
* The returned collection does <i>not</i> pass the hashCode and equals
* operations through to the backing collection, but relies on
* <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods. This
* is necessary to preserve the contracts of these operations in the case
* that the backing collection is a set or a list.<p>
*
* The returned collection will be serializable if the specified collection
* is serializable.
*
* @param <T> the class of the objects in the collection
* @param c the collection for which an unmodifiable view is to be
* returned.
* @return an unmodifiable view of the specified collection.
*/
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
return new UnmodifiableCollection<>(c);
}
看一下这个实例
UnmodifiableCollection(Collection<? extends E> c) {
if (c==null)
throw new NullPointerException();
this.c = c;
}
所以最终会抛出异常
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
at test.main(test.java:11)