我们通过Collections.unmodifiableX来得到只读容器,因为容器被设为只读的,所以必须填入有意义的数据之后才进行设置
import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.Collections;import java.util.HashSet;import java.util.List;import java.util.Set;/* * 创建只读容器 */public class Test{ public static Collectiondata = new ArrayList (Arrays.asList("AAA BBB CCC DDD".split(" "))); public static void main(String[] args) { Collection c = Collections.unmodifiableCollection(data); System.out.println(c); //c.add("EEE"); List list = Collections.unmodifiableList(new ArrayList (data)); System.out.println(list); //list.add("EEE"); Set s = Collections.unmodifiableSet(new HashSet (data)); System.out.println(s); //s.add("EEE"); /* Collections.unmodifiableSortedMap(m); Collections.unmodifiableMap(m); Collections.unmodifiableSortedMap(m); */ }}
我们可以通过Collections.synchronizedX来创建线程同步的容器
import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.Collections;import java.util.HashSet;import java.util.List;import java.util.Set;/* * 创建同步容器 */public class Test{ public static Collectiondata = new ArrayList (Arrays.asList("AAA BBB CCC DDD".split(" "))); public static void main(String[] args) { Collection c = Collections.synchronizedCollection(data); List list = Collections.synchronizedList(new ArrayList (data)); list.add("AAA"); list.add("BB"); /* * Collections.synchronizedMap(m); * Collections.synchronizedSortedMap(m); * Collections.synchronizedSet(s); * Collections.synchronizedSortedSet(s); */ }}