enumeration(Collection) | Produces an old-style Enumeration for the argument. |
max(Collection) min(Collection) | Produces the maximum or minimum element in the argument using the natural comparison method of the objects in the Collection. |
max(Collection, Comparator) min(Collection, Comparator) | Produces the maximum or minimum element in the Collection using the Comparator. |
nCopies(int n, Object o) | Returns an immutable List of size n whose handles all point to o. |
subList(List, int min, int max) | Returns a new List backed by the specified argument List that is a window into that argument with indexes starting at min and stopping just before max. |
对于每种情况,在将其正式变为只读以前,都必须用有有效的数据填充容器。一旦载入成功,最佳的做法就是用“不可修改”调用产生的句柄替换现有的句柄。这样做可有效避免将其变成不可修改后不慎改变其中的内容。在另一方面,该工具也允许我们在一个类中将能够修改的容器保持为private状态,并可从一个方法调用中返回指向那个容器的一个只读句柄。这样一来,虽然我们可在类里修改它,但其他任何人都只能读。//: ReadOnly.java// Using the Collections.unmodifiable methodspackage c08.newcollections;import java.util.*;public class ReadOnly {public static void main(String[] args) {Collection c = new ArrayList();Collection1.fill(c); // Insert useful datac = Collections.unmodifiableCollection(c);Collection1.print(c); // Reading is OK//! c.add("one"); // Can"t change itList a = new ArrayList();Collection1.fill(a);a = Collections.unmodifiableList(a);ListIterator lit = a.listIterator();System.out.println(lit.next()); // Reading OK//! lit.add("one"); // Can"t change itSet s = new HashSet();Collection1.fill(s);s = Collections.unmodifiableSet(s);Collection1.print(s); // Reading OK//! s.add("one"); // Can"t change itMap m = new HashMap();Map1.fill(m, Map1.testData1);m = Collections.unmodifiableMap(m);Map1.print(m); // Reading OK//! m.put("Ralph", "Howdy!");}} ///:~
//: Synchronization.java// Using the Collections.synchronized methodspackage c08.newcollections;import java.util.*;public class Synchronization {public static void main(String[] args) {Collection c = Collections.synchronizedCollection(new ArrayList());List list = Collections.synchronizedList(new ArrayList());Set s = Collections.synchronizedSet(new HashSet());Map m = Collections.synchronizedMap(new HashMap());}} ///:~