有的时候创建一个具有只读属性的Collection 或 Map,会带来很多方便。Collections 类可以帮我们实现这个目的,它有一个方法,参数为原本的容器,返回的容器是具有只读属性的容器。可以应用于Collection、List、Map、Set。
下面是关于Collections 类的具体方法:
static < T > Collection< T > unmodifiableCollection(Collection< ? extends T> c)
返回指定 collection 的不可修改视图。
static < T > List< T > unmodifiableList(List< ? extends T> list)
返回指定列表的不可修改视图。
static < K,V> Map< K,V> unmodifiableMap(Map< ? extends K,? extends V> m)
返回指定映射的不可修改视图。
static < T > Set< T > unmodifiableSet(Set< ? extends T> s)
返回指定 set 的不可修改视图。
static < K,V> SortedMap< K,V> unmodifiableSortedMap(SortedMap< K,? extends V> m)
返回指定有序映射的不可修改视图。
static < T > SortedSet< T > unmodifiableSortedSet(SortedSet< T > s)
返回指定有序 set 的不可修改视图。
下面是一个实现的例子:设置为只读属性后,如果你执行其他添加或者删除动作,你将在运行时期得到一个 java.lang.UnsupportedOperationException 异常。
import java.util.*;
/** 设置只读Collection */
public class ReadOnly {
public static void main(String[] args) {
String[] strArray = {"Hello","World"};
List<String> list = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(strArray)));
// list.add("Jas");
// list.remove(1);
System.out.println(list);
Integer[] intArray = {1,2,3,4,5};
Set<Integer> set = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(intArray)));
//set.add(6);
System.out.println(set);
Map<String,Integer> map1 = new HashMap<>();
map1.put("one",1);
map1.put("two",2);
Map<String,Integer> map2 = Collections.unmodifiableMap(map1);
// map2.put("three",3);
System.out.println(map2);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
对特定类型的“不可修改的”方法调用并不会在编译期进行检查,但是在转换完成后,任何会改变容器内元素内容的操作都会报异常。所以在将容器设为只读属性之前,必须填入有意义的数据。不过此方法允许你保留一份可以修改的容器,作为类的private 属性,然后通过某个方法调用返回该容器的“只读”的引用。这样你就可以修改容器中的内容,而别人只能读取。