集合框架源码分析四(Collections类详细分析)

我认为Collections类主要是完成了两个主要功能
1.提供了若干简单而又有用的算法,比如排序,二分查找,求最大最小值等等。
2.提供对集合进行包装的静态方法。比如把指定的集合包装成线程安全的集合、包装成不可修改的集合、包装成类型安全的集合等。

Java代码   收藏代码
  1. package java.util;  
  2. import java.io.Serializable;  
  3. import java.io.ObjectOutputStream;  
  4. import java.io.IOException;  
  5. import java.lang.reflect.Array;  
  6.   
  7.   
  8. public class Collections{  
  9.     // Suppresses default constructor, ensuring non-instantiability.  
  10.     private Collections() {  
  11.     }  
  12.   
  13.     // 算法  
  14.   
  15.     /* 
  16.      *  
  17.      * 算法需要用到的一些参数。所有的关于List的算法都有两种实现,一种是适合随机访问的 
  18.      * List,另一种是适合连续访问的。 
  19.      */  
  20.     private static final int BINARYSEARCH_THRESHOLD   = 5000;  
  21.     private static final int REVERSE_THRESHOLD        =   18;  
  22.     private static final int SHUFFLE_THRESHOLD        =    5;  
  23.     private static final int FILL_THRESHOLD           =   25;  
  24.     private static final int ROTATE_THRESHOLD         =  100;  
  25.     private static final int COPY_THRESHOLD           =   10;  
  26.     private static final int REPLACEALL_THRESHOLD     =   11;  
  27.     private static final int INDEXOFSUBLIST_THRESHOLD =   35;  
  28.   
  29.     /** 
  30.      * 
  31.      * List中的所有元素必须实现Compareable接口,即每个 元素必须是可比的。 
  32.      *  
  33.      * 算法的实现原理为: 
  34.      * 把指定的List转化为一个对象数组,对数组进行排序,然后迭代List的每一个元素, 
  35.      * 在同样的位置重新设置数组中排好序的元素 
  36.      */  
  37.     public static <T extends Comparable<? super T>> void sort(List<T> list) {  
  38.         Object[] a = list.toArray();    //转化为对象数组  
  39.         Arrays.sort(a);                 //对数组排序,使用了归并排序.对此归并的详细分析可见我另一篇博客  
  40.         ListIterator<T> i = list.listIterator();  
  41.         for (int j=0; j<a.length; j++) { //迭代元素  
  42.             i.next();  
  43.             i.set((T)a[j]);     //在同样的位置重设排好序的值  
  44.         }  
  45.     }  
  46.       
  47.       
  48.   
  49.     /** 
  50.      * 传一个实现了Comparator接口的对象进来。 
  51.      * c.compare(o1,o2);来比较两个元素 
  52.      */  
  53.     public static <T> void sort(List<T> list, Comparator<? super T> c) {  
  54.         Object[] a = list.toArray();  
  55.         Arrays.sort(a, (Comparator)c);  
  56.         ListIterator i = list.listIterator();  
  57.         for (int j=0; j<a.length; j++) {  
  58.             i.next();  
  59.             i.set(a[j]);  
  60.         }  
  61.     }  
  62.   
  63.   
  64.     /** 
  65.      * 
  66.      * 使用二分查找在指定List中查找指定元素key。 
  67.      * List中的元素必须是有序的。如果List中有多个key,不能确保哪个key值被找到。 
  68.      * 如果List不是有序的,返回的值没有任何意义 
  69.      *  
  70.      * 对于随机访问列表来说,时间复杂度为O(log(n)),比如1024个数只需要查找log2(1024)=10次, 
  71.      * log2(n)是最坏的情况,即最坏的情况下都只需要找10次 
  72.      * 对于链表来说,查找中间元素的时间复杂度为O(n),元素比较的时间复杂度为O(log(n)) 
  73.      *  
  74.      * @return 查找元素的索引。如果返回的是负数表明找不到此元素,但可以用返回值计算 
  75.      *        应该将key插入到集合什么位置,任然能使集合有序(如果需要插入key值的话)。 
  76.      *      公式:point  = -i - 1 
  77.      *  
  78.      */  
  79.     public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) {  
  80.         if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)  
  81.             return Collections.indexedBinarySearch(list, key);  
  82.         else  
  83.             return Collections.iteratorBinarySearch(list, key);  
  84.     }  
  85.   
  86.     /** 
  87.      * 使用索引化二分查找。 
  88.      * size小于5000的链表也用此方法查找 
  89.      */  
  90.     private static <T> int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key){  
  91.         int low = 0;    //元素所在范围的下界  
  92.         int high = list.size()-1;   //上界  
  93.       
  94.         while (low <= high) {  
  95.             int mid = (low + high) >>> 1;  
  96.             Comparable<? super T> midVal = list.get(mid); //中间值  
  97.             int cmp = midVal.compareTo(key);    //指定元素与中间值比较  
  98.       
  99.             if (cmp < 0)  
  100.                 low = mid + 1;  //重新设置上界和下界  
  101.             else if (cmp > 0)  
  102.                 high = mid - 1;  
  103.             else  
  104.                 return mid; // key found  
  105.         }  
  106.         return -(low + 1);  // key not found  
  107.     }  
  108.   
  109.     /** 
  110.      * 迭代式二分查找,线性查找,依次查找得中间值 
  111.      *  
  112.      */  
  113.     private static <T> int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key){  
  114.         int low = 0;  
  115.         int high = list.size()-1;  
  116.             ListIterator<? extends Comparable<? super T>> i = list.listIterator();  
  117.       
  118.             while (low <= high) {  
  119.                 int mid = (low + high) >>> 1;  
  120.                 Comparable<? super T> midVal = get(i, mid);  
  121.                 int cmp = midVal.compareTo(key);  
  122.       
  123.                 if (cmp < 0)  
  124.                     low = mid + 1;  
  125.                 else if (cmp > 0)  
  126.                     high = mid - 1;  
  127.                 else  
  128.                     return mid; // key found  
  129.             }  
  130.             return -(low + 1);  // key not found  
  131.     }  
  132.   
  133.   
  134.     private static <T> T get(ListIterator<? extends T> i, int index) {  
  135.     T obj = null;  
  136.         int pos = i.nextIndex();    //根据当前迭代器的位置确定是向前还是向后遍历找中间值  
  137.         if (pos <= index) {  
  138.             do {  
  139.                 obj = i.next();  
  140.             } while (pos++ < index);  
  141.         } else {  
  142.             do {  
  143.                 obj = i.previous();  
  144.             } while (--pos > index);  
  145.         }  
  146.         return obj;  
  147.     }  
  148.   
  149.     /** 
  150.      * 提供实现了Comparator接口的对象比较元素 
  151.      */  
  152.     public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {  
  153.         if (c==null)  
  154.             return binarySearch((List) list, key);  
  155.   
  156.         if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)  
  157.             return Collections.indexedBinarySearch(list, key, c);  
  158.         else  
  159.             return Collections.iteratorBinarySearch(list, key, c);  
  160.     }  
  161.   
  162.     private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {  
  163.         int low = 0;  
  164.         int high = l.size()-1;  
  165.       
  166.         while (low <= high) {  
  167.             int mid = (low + high) >>> 1;  
  168.             T midVal = l.get(mid);  
  169.             int cmp = c.compare(midVal, key);  
  170.       
  171.             if (cmp < 0)  
  172.             low = mid + 1;  
  173.             else if (cmp > 0)  
  174.             high = mid - 1;  
  175.             else  
  176.             return mid; // key found  
  177.         }  
  178.         return -(low + 1);  // key not found  
  179.     }  
  180.   
  181.     private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {  
  182.         int low = 0;  
  183.         int high = l.size()-1;  
  184.             ListIterator<? extends T> i = l.listIterator();  
  185.       
  186.             while (low <= high) {  
  187.                 int mid = (low + high) >>> 1;  
  188.                 T midVal = get(i, mid);  
  189.                 int cmp = c.compare(midVal, key);  
  190.       
  191.                 if (cmp < 0)  
  192.                     low = mid + 1;  
  193.                 else if (cmp > 0)  
  194.                     high = mid - 1;  
  195.                 else  
  196.                     return mid; // key found  
  197.             }  
  198.             return -(low + 1);  // key not found  
  199.     }  
  200.   
  201.     private interface SelfComparable extends Comparable<SelfComparable> {}  
  202.   
  203.   
  204.     /** 
  205.      *  
  206.      * 逆序排列指定列表中的元素 
  207.      */  
  208.     public static void reverse(List<?> list) {  
  209.         int size = list.size();  
  210.         //如果是size小于18的链表或是基于随机访问的列表  
  211.         if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {  
  212.             for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)  //第一个与最后一个,依次交换  
  213.                 swap(list, i, j);   //交换i和j位置的值  
  214.         } else {    //基于迭代器的逆序排列算法  
  215.             ListIterator fwd = list.listIterator();  
  216.             ListIterator rev = list.listIterator(size);  
  217.             for (int i=0, mid=list.size()>>1; i<mid; i++) {    //这..,一个思想你懂得  
  218.                 Object tmp = fwd.next();  
  219.                 fwd.set(rev.previous());  
  220.                 rev.set(tmp);  
  221.             }  
  222.         }  
  223.     }  
  224.   
  225.     /** 
  226.      *  
  227.      * 对指定列表中的元素进行混排 
  228.      */  
  229.     public static void shuffle(List<?> list) {  
  230.         if (r == null) {  
  231.             r = new Random();  
  232.         }  
  233.         shuffle(list, r);  
  234.     }  
  235.     private static Random r;  
  236.   
  237.     /** 
  238.      *  
  239.      * 提供一个随机数生成器对指定List进行混排 
  240.      *  
  241.      * 基本算法思想为: 
  242.      * 逆向遍历list,从最后一个元素到第二个元素,然后重复交换当前位置 
  243.      * 与随机产生的位置的元素值。 
  244.      * 
  245.      * 如果list不是基于随机访问并且其size>5,会先把List中的复制到数组中, 
  246.      * 然后对数组进行混排,再把数组中的元素重新填入List中。 
  247.      * 这样做为了避免迭代器大跨度查找元素影响效率 
  248.      */  
  249.     public static void shuffle(List<?> list, Random rnd) {  
  250.         int size = list.size();  
  251.         if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {  
  252.             for (int i=size; i>1; i--)   //从i-1个位置开始与随机位置元素交换值  
  253.                 swap(list, i-1, rnd.nextInt(i));  
  254.         } else {  
  255.             Object arr[] = list.toArray();  //先转化为数组  
  256.   
  257.             //对数组进行混排  
  258.             for (int i=size; i>1; i--)  
  259.                 swap(arr, i-1, rnd.nextInt(i));  
  260.   
  261.             // 然后把数组中的元素重新填入List  
  262.             ListIterator it = list.listIterator();  
  263.             for (int i=0; i<arr.length; i++) {  
  264.                 it.next();  
  265.                 it.set(arr[i]);  
  266.             }  
  267.         }  
  268.     }  
  269.   
  270.     /** 
  271.      * 交换List中两个位置的值 
  272.      */  
  273.     public static void swap(List<?> list, int i, int j) {  
  274.         final List l = list;  
  275.         l.set(i, l.set(j, l.get(i)));   //互换i和j位置的值  
  276.     }  
  277.   
  278.     /** 
  279.      * 交换数组俩位置的值。好熟悉啊 
  280.      */  
  281.     private static void swap(Object[] arr, int i, int j) {  
  282.         Object tmp = arr[i];  
  283.         arr[i] = arr[j];  
  284.         arr[j] = tmp;  
  285.     }  
  286.   
  287.     /** 
  288.      *  
  289.      * 用obj替换List中的所有元素 
  290.      * 依次遍历赋值即可 
  291.      */  
  292.     public static <T> void fill(List<? super T> list, T obj) {  
  293.         int size = list.size();  
  294.   
  295.         if (size < FILL_THRESHOLD || list instanceof RandomAccess) {  
  296.             for (int i=0; i<size; i++)  
  297.                 list.set(i, obj);  
  298.         } else {  
  299.             ListIterator<? super T> itr = list.listIterator();  
  300.             for (int i=0; i<size; i++) {  
  301.                 itr.next();  
  302.                 itr.set(obj);  
  303.             }  
  304.         }  
  305.     }  
  306.   
  307.     /** 
  308.      *  
  309.      * 复制源列表的所有元素到目标列表, 
  310.      * 如果src.size > dest.size 将抛出一个异常 
  311.      * 如果src.size < dest.size dest中多出的元素将不受影响 
  312.      * 同样是依次遍历赋值 
  313.      */  
  314.     public static <T> void copy(List<? super T> dest, List<? extends T> src) {  
  315.         int srcSize = src.size();  
  316.         if (srcSize > dest.size())     
  317.             throw new IndexOutOfBoundsException("Source does not fit in dest");  
  318.   
  319.         if (srcSize < COPY_THRESHOLD ||  
  320.             (src instanceof RandomAccess && dest instanceof RandomAccess)) {  
  321.             for (int i=0; i<srcSize; i++)  
  322.                 dest.set(i, src.get(i));  
  323.         } else {    //一个链表一个线性表也可以用迭代器赋值  
  324.             ListIterator<? super T> di=dest.listIterator();  
  325.             ListIterator<? extends T> si=src.listIterator();  
  326.             for (int i=0; i<srcSize; i++) {  
  327.                 di.next();  
  328.                 di.set(si.next());  
  329.             }  
  330.         }  
  331.     }  
  332.   
  333.     /** 
  334.      *  
  335.      * 返回集合中的最小元素。前提是其中的元素都是可比的,即实现了Comparable接口 
  336.      * 找出一个通用的算法其实不容易,尽管它的思想不难。 
  337.      * 反正要依次遍历完所有元素,所以直接用了迭代器 
  338.      */  
  339.     public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {  
  340.         Iterator<? extends T> i = coll.iterator();  
  341.         T candidate = i.next();  
  342.         while (i.hasNext()) {  
  343.             T next = i.next();  
  344.             if (next.compareTo(candidate) < 0)  
  345.                 candidate = next;  
  346.         }  
  347.         return candidate;  
  348.     }  
  349.   
  350.     /** 
  351.      * 根据提供的比较器求最小元素 
  352.      */  
  353.     public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {  
  354.         if (comp==null)  
  355.             //返回默认比较器,其实默认比较器什么也不做,只是看集合元素是否实现了Comparable接口,  
  356.             //否则抛出ClassCastException  
  357.             return (T)min((Collection<SelfComparable>) (Collection) coll);  
  358.   
  359.         Iterator<? extends T> i = coll.iterator();  
  360.         T candidate = i.next();  //假设第一个元素为最小元素  
  361.   
  362.         while (i.hasNext()) {  
  363.             T next = i.next();  
  364.             if (comp.compare(next, candidate) < 0)  
  365.                 candidate = next;  
  366.         }  
  367.         return candidate;  
  368.     }  
  369.   
  370.     /** 
  371.      * 求集合中最大元素 
  372.      */  
  373.     public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {  
  374.         Iterator<? extends T> i = coll.iterator();  
  375.         T candidate = i.next();  
  376.       
  377.         while (i.hasNext()) {  
  378.             T next = i.next();  
  379.             if (next.compareTo(candidate) > 0)  
  380.                 candidate = next;  
  381.         }  
  382.         return candidate;  
  383.     }  
  384.   
  385.     /** 
  386.      * 根据指定比较器求集合中最大元素 
  387.      */  
  388.     public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {  
  389.         if (comp==null)   
  390.             return (T)max((Collection<SelfComparable>) (Collection) coll);  
  391.   
  392.         Iterator<? extends T> i = coll.iterator();  
  393.         T candidate = i.next();  
  394.   
  395.         while (i.hasNext()) {  
  396.             T next = i.next();  
  397.             if (comp.compare(next, candidate) > 0)  
  398.                 candidate = next;  
  399.         }  
  400.     return candidate;  
  401.     }  
  402.   
  403.     /** 
  404.      *  
  405.      * 旋转移位List中的元素通过指定的distance。每个元素移动后的位置为: 
  406.      * (i + distance)%list.size.此方法不会改变列表的长度 
  407.      *  
  408.      * 比如,类表元素为: [t, a, n, k, s , w] 
  409.      * 执行Collections.rotate(list, 2)或 
  410.      * Collections.rotate(list, -4)后, list中的元素将变为 
  411.      * [s, w, t, a, n , k]。可以这样理解:正数表示向后移,负数表示向前移 
  412.      * 
  413.      */  
  414.     public static void rotate(List<?> list, int distance) {  
  415.         if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)  
  416.             rotate1((List)list, distance);  
  417.         else  
  418.             rotate2((List)list, distance);  
  419.     }  
  420.   
  421.     private static <T> void rotate1(List<T> list, int distance) {  
  422.         int size = list.size();  
  423.         if (size == 0)  
  424.             return;  
  425.         distance = distance % size; //distance始终处于0到size(不包括)之间  
  426.         if (distance < 0)  
  427.             distance += size;   //还是以向后移来计算的  
  428.         if (distance == 0)  
  429.             return;  
  430.   
  431.         for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {  
  432.             T displaced = list.get(cycleStart);  
  433.             int i = cycleStart;  
  434.             do {      
  435.                 i += distance;  //求新位置  
  436.                 if (i >= size)  
  437.                     i -= size;  //超出size就减去size  
  438.                 displaced = list.set(i, displaced); //为新位置赋原来的值  
  439.                 nMoved ++;  //如果等于size证明全部替换完毕  
  440.             } while(i != cycleStart); //依次类推,求新位置的新位置  
  441.         }  
  442.     }  
  443.   
  444.     private static void rotate2(List<?> list, int distance) {  
  445.         int size = list.size();  
  446.         if (size == 0)  
  447.             return;  
  448.         int mid =  -distance % size;  
  449.         if (mid < 0)  
  450.             mid += size;  
  451.         if (mid == 0)  
  452.             return;  
  453.         //好神奇啊  
  454.         reverse(list.subList(0, mid));  
  455.         reverse(list.subList(mid, size));  
  456.         reverse(list);  
  457.     }  
  458.   
  459.     /** 
  460.      *  
  461.      * 把指定集合中所有与oladVal相等的元素替换成newVal 
  462.      * 只要list发生了改变就返回true 
  463.      */  
  464.     public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {  
  465.         boolean result = false;  
  466.         int size = list.size();  
  467.         if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {  
  468.             if (oldVal==null) {  
  469.                 for (int i=0; i<size; i++) {  
  470.                     if (list.get(i)==null) {  
  471.                         list.set(i, newVal);  
  472.                         result = true;  
  473.                     }  
  474.                 }  
  475.             } else {  
  476.                 for (int i=0; i<size; i++) {  
  477.                     if (oldVal.equals(list.get(i))) {  
  478.                         list.set(i, newVal);  
  479.                         result = true;  
  480.                     }  
  481.                 }  
  482.             }  
  483.         } else {  
  484.             ListIterator<T> itr=list.listIterator();  
  485.             if (oldVal==null) {  
  486.                 for (int i=0; i<size; i++) {  
  487.                     if (itr.next()==null) {  
  488.                         itr.set(newVal);  
  489.                         result = true;  
  490.                     }  
  491.                 }  
  492.             } else {  
  493.                 for (int i=0; i<size; i++) {  
  494.                     if (oldVal.equals(itr.next())) {  
  495.                         itr.set(newVal);  
  496.                         result = true;  
  497.                     }  
  498.                 }  
  499.             }  
  500.         }  
  501.         return result;  
  502.     }  
  503.   
  504.     /** 
  505.      *  
  506.      * target是否是source的子集,如果是返回target第一个元素的索引, 
  507.      * 否则返回-1。 
  508.      * 其实这里和串的模式匹配差不多。这里使用的是基本的回溯法。 
  509.      *  
  510.      */  
  511.     public static int indexOfSubList(List<?> source, List<?> target) {  
  512.         int sourceSize = source.size();  
  513.         int targetSize = target.size();  
  514.         int maxCandidate = sourceSize - targetSize;  
  515.   
  516.         if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||  
  517.             (source instanceof RandomAccess&&target instanceof RandomAccess)) {  
  518.    nextCand:for (int candidate = 0; candidate <= maxCandidate; candidate++) {  
  519.                 for (int i=0, j=candidate; i<targetSize; i++, j++)  
  520.                     if (!eq(target.get(i), source.get(j)))  
  521.                         continue nextCand;  // 元素失配,跳到外部循环  
  522.                 return candidate;  // All elements of candidate matched target  
  523.             }  
  524.         } else {  // Iterator version of above algorithm  
  525.             ListIterator<?> si = source.listIterator();  
  526.    nextCand:for (int candidate = 0; candidate <= maxCandidate; candidate++) {  
  527.                 ListIterator<?> ti = target.listIterator();  
  528.                 for (int i=0; i<targetSize; i++) {  
  529.                     if (!eq(ti.next(), si.next())) {  
  530.                         // 回溯指针,然后跳到外部循环继续执行  
  531.                         for (int j=0; j<i; j++)  
  532.                             si.previous();  
  533.                         continue nextCand;  
  534.                     }  
  535.                 }  
  536.                 return candidate;  
  537.             }  
  538.         }  
  539.         return -1;  //没有找到匹配的子串返回-1  
  540.     }  
  541.   
  542.     /** 
  543.      * 如果有一个或多个字串,返回最后一个出现的子串的第一个元素的索引 
  544.      */  
  545.     public static int lastIndexOfSubList(List<?> source, List<?> target) {  
  546.         int sourceSize = source.size();  
  547.         int targetSize = target.size();  
  548.         int maxCandidate = sourceSize - targetSize;  
  549.   
  550.         if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||  
  551.             source instanceof RandomAccess) {   // Index access version  
  552.    nextCand:for (int candidate = maxCandidate; candidate >= 0; candidate--) {  
  553.                 for (int i=0, j=candidate; i<targetSize; i++, j++)  
  554.                     if (!eq(target.get(i), source.get(j)))  //从source的maxCandidate位置开始比较。然后是maxCandidate-1,依次类推  
  555.                         continue nextCand;  // Element mismatch, try next cand  
  556.                 return candidate;  // All elements of candidate matched target  
  557.             }  
  558.         } else {  // Iterator version of above algorithm  
  559.             if (maxCandidate < 0)  
  560.                 return -1;  
  561.             ListIterator<?> si = source.listIterator(maxCandidate);  
  562.   nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) {  
  563.                 ListIterator<?> ti = target.listIterator();  
  564.                 for (int i=0; i<targetSize; i++) {  
  565.                     if (!eq(ti.next(), si.next())) {  
  566.                         if (candidate != 0) {  
  567.                             // Back up source iterator to next candidate  
  568.                             for (int j=0; j<=i+1; j++)  
  569.                                 si.previous();  
  570.                         }  
  571.                         continue nextCand;  
  572.                     }  
  573.                 }  
  574.                 return candidate;  
  575.             }  
  576.         }  
  577.         return -1;  // No candidate matched the target  
  578.     }  
  579.   
  580.   
  581.     // Unmodifiable Wrappers  
  582.   
  583.     /** 
  584.      *  
  585.      * 返回一个关于指定集合的不可修改的视图。 
  586.      * 任何试图修改该视图的操作都将抛出一个UnsupportedOperationException 
  587.      *  
  588.      * Collection返回的视图的equals方法不是调用底层集合的equals方法 
  589.      * 而是继承了Object的equals方法。hashCode方法也是一样的。 
  590.      * 因为Set和List的equals方法并不相同。 
  591.      */  
  592.     public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {  
  593.         return new UnmodifiableCollection<T>(c);  
  594.     }  
  595.   
  596.       
  597.     static class UnmodifiableCollection<E> implements Collection<E>, Serializable {  
  598.         // use serialVersionUID from JDK 1.2.2 for interoperability  
  599.         private static final long serialVersionUID = 1820017752578914078L;  
  600.       
  601.         final Collection<? extends E> c;  
  602.       
  603.         UnmodifiableCollection(Collection<? extends E> c) {  
  604.                 if (c==null)  
  605.                     throw new NullPointerException();  
  606.                 this.c = c;  
  607.         }  
  608.       
  609.         public int size()           {return c.size();}  
  610.         public boolean isEmpty()        {return c.isEmpty();}  
  611.         public boolean contains(Object o)   {return c.contains(o);}  
  612.         public Object[] toArray()           {return c.toArray();}  
  613.         public <T> T[] toArray(T[] a)       {return c.toArray(a);}  
  614.         public String toString()            {return c.toString();}  
  615.       
  616.         public Iterator<E> iterator() {  
  617.             return new Iterator<E>() {  
  618.                 Iterator<? extends E> i = c.iterator();  
  619.           
  620.                 public boolean hasNext() {return i.hasNext();}  
  621.                 public E next()      {return i.next();}  
  622.                 public void remove() {  //试图修改集合的操作都将抛出此异常  
  623.                     throw new UnsupportedOperationException();  
  624.                 }  
  625.             };  
  626.             }  
  627.       
  628.         public boolean add(E e){  
  629.             throw new UnsupportedOperationException();  
  630.         }  
  631.         public boolean remove(Object o) {  
  632.             throw new UnsupportedOperationException();  
  633.         }  
  634.       
  635.         public boolean containsAll(Collection<?> coll) {  
  636.             return c.containsAll(coll);  
  637.         }  
  638.         public boolean addAll(Collection<? extends E> coll) {  
  639.             throw new UnsupportedOperationException();  
  640.         }  
  641.         public boolean removeAll(Collection<?> coll) {  
  642.             throw new UnsupportedOperationException();  
  643.         }  
  644.         public boolean retainAll(Collection<?> coll) {  
  645.             throw new UnsupportedOperationException();  
  646.         }  
  647.         public void clear() {  
  648.             throw new UnsupportedOperationException();  
  649.         }  
  650.     }  
  651.   
  652.     /** 
  653.      * 返回一个不可修改Set。 
  654.      * 调用的是底层集合的equals方法 
  655.      */  
  656.     public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {  
  657.         return new UnmodifiableSet<T>(s);  
  658.     }  
  659.   
  660.     /** 
  661.      * @serial include 
  662.      */  
  663.     static class UnmodifiableSet<E> extends UnmodifiableCollection<E>  
  664.                      implements Set<E>, Serializable {  
  665.         private static final long serialVersionUID = -9215047833775013803L;  
  666.       
  667.         UnmodifiableSet(Set<? extends E> s)   {super(s);}  
  668.         public boolean equals(Object o) {return o == this || c.equals(o);}  
  669.         public int hashCode()       {return c.hashCode();}  
  670.     }  
  671.   
  672.     /** 
  673.      * 返回一个不可修改的Sort Set 
  674.      */  
  675.     public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {  
  676.         return new UnmodifiableSortedSet<T>(s);  
  677.     }  
  678.   
  679.     static class UnmodifiableSortedSet<E>  
  680.                          extends UnmodifiableSet<E>  
  681.                          implements SortedSet<E>, Serializable {  
  682.         private static final long serialVersionUID = -4929149591599911165L;  
  683.         private final SortedSet<E> ss;  
  684.   
  685.         UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}  
  686.   
  687.         public Comparator<? super E> comparator() {return ss.comparator();}  
  688.   
  689.         public SortedSet<E> subSet(E fromElement, E toElement) {  
  690.             return new UnmodifiableSortedSet<E>(ss.subSet(fromElement,toElement));  
  691.         }  
  692.         public SortedSet<E> headSet(E toElement) {  
  693.             return new UnmodifiableSortedSet<E>(ss.headSet(toElement));  
  694.         }  
  695.         public SortedSet<E> tailSet(E fromElement) {  
  696.             return new UnmodifiableSortedSet<E>(ss.tailSet(fromElement));  
  697.         }  
  698.   
  699.         public E first()               {return ss.first();}  
  700.         public E last()                {return ss.last();}  
  701.     }  
  702.   
  703.     /** 
  704.      * 返回一个 不可修改的List 
  705.      * 如果原List实现了RandomAccess接口,返回的List也将实现此接口 
  706.      */  
  707.     public static <T> List<T> unmodifiableList(List<? extends T> list) {  
  708.         return (list instanceof RandomAccess ?  
  709.                     new UnmodifiableRandomAccessList<T>(list) :  
  710.                     new UnmodifiableList<T>(list));  
  711.     }  
  712.   
  713.   
  714.     static class UnmodifiableList<E> extends UnmodifiableCollection<E>  
  715.                       implements List<E> {  
  716.         static final long serialVersionUID = -283967356065247728L;  
  717.         final List<? extends E> list;  
  718.       
  719.         UnmodifiableList(List<? extends E> list) {  
  720.             super(list);  
  721.             this.list = list;  
  722.         }  
  723.       
  724.         public boolean equals(Object o) {return o == this || list.equals(o);}  
  725.         public int hashCode()       {return list.hashCode();}  
  726.       
  727.         public E get(int index) {return list.get(index);}  
  728.         public E set(int index, E element) {  
  729.             throw new UnsupportedOperationException();  
  730.             }  
  731.         public void add(int index, E element) {  
  732.             throw new UnsupportedOperationException();  
  733.             }  
  734.         public E remove(int index) {  
  735.             throw new UnsupportedOperationException();  
  736.             }  
  737.         public int indexOf(Object o)            {return list.indexOf(o);}  
  738.         public int lastIndexOf(Object o)        {return list.lastIndexOf(o);}  
  739.         public boolean addAll(int index, Collection<? extends E> c) {  
  740.             throw new UnsupportedOperationException();  
  741.             }  
  742.         public ListIterator<E> listIterator()     {return listIterator(0);}  
  743.       
  744.         public ListIterator<E> listIterator(final int index) {  
  745.             return new ListIterator<E>() {  
  746.             ListIterator<? extends E> i = list.listIterator(index);  
  747.       
  748.             public boolean hasNext()     {return i.hasNext();}  
  749.             public E next()          {return i.next();}  
  750.             public boolean hasPrevious() {return i.hasPrevious();}  
  751.             public E previous()      {return i.previous();}  
  752.             public int nextIndex()       {return i.nextIndex();}  
  753.             public int previousIndex()   {return i.previousIndex();}  
  754.       
  755.             public void remove() {  
  756.                 throw new UnsupportedOperationException();  
  757.                     }  
  758.             public void set(E e) {  
  759.                 throw new UnsupportedOperationException();  
  760.                     }  
  761.             public void add(E e) {  
  762.                 throw new UnsupportedOperationException();  
  763.                     }  
  764.             };  
  765.         }  
  766.   
  767.         public List<E> subList(int fromIndex, int toIndex) {  
  768.                 return new UnmodifiableList<E>(list.subList(fromIndex, toIndex));  
  769.         }  
  770.   
  771.         /** 
  772.          * UnmodifiableRandomAccessList instances are serialized as 
  773.          * UnmodifiableList instances to allow them to be deserialized 
  774.          * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList). 
  775.          * This method inverts the transformation.  As a beneficial 
  776.          * side-effect, it also grafts the RandomAccess marker onto 
  777.          * UnmodifiableList instances that were serialized in pre-1.4 JREs. 
  778.          * 
  779.          * Note: Unfortunately, UnmodifiableRandomAccessList instances 
  780.          * serialized in 1.4.1 and deserialized in 1.4 will become 
  781.          * UnmodifiableList instances, as this method was missing in 1.4. 
  782.          * 这个,自己看吧... 
  783.          */  
  784.         private Object readResolve() {  
  785.             return (list instanceof RandomAccess  
  786.             ? new UnmodifiableRandomAccessList<E>(list)  
  787.             : this);  
  788.         }  
  789.     }  
  790.   
  791.       
  792.     static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>  
  793.                                               implements RandomAccess{  
  794.         UnmodifiableRandomAccessList(List<? extends E> list) {  
  795.             super(list);  
  796.         }  
  797.   
  798.         public List<E> subList(int fromIndex, int toIndex) {  
  799.             return new UnmodifiableRandomAccessList<E>(  
  800.                 list.subList(fromIndex, toIndex));  
  801.         }  
  802.   
  803.         private static final long serialVersionUID = -2542308836966382001L;  
  804.   
  805.         /** 
  806.          * Allows instances to be deserialized in pre-1.4 JREs (which do 
  807.          * not have UnmodifiableRandomAccessList).  UnmodifiableList has 
  808.          * a readResolve method that inverts this transformation upon 
  809.          * deserialization. 
  810.          */  
  811.         private Object writeReplace() {  
  812.             return new UnmodifiableList<E>(list);  
  813.         }  
  814.     }  
  815.   
  816.     /** 
  817.      * 返回一个不可修改的map 
  818.      */  
  819.     public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {  
  820.         return new UnmodifiableMap<K,V>(m);  
  821.     }  
  822.   
  823.   
  824.     private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {  
  825.     // use serialVersionUID from JDK 1.2.2 for interoperability  
  826.         private static final long serialVersionUID = -1034234728574286014L;  
  827.       
  828.         private final Map<? extends K, ? extends V> m;  
  829.       
  830.         UnmodifiableMap(Map<? extends K, ? extends V> m) {  
  831.                 if (m==null)  
  832.                     throw new NullPointerException();  
  833.                 this.m = m;  
  834.         }  
  835.       
  836.         public int size()                {return m.size();}  
  837.         public boolean isEmpty()             {return m.isEmpty();}  
  838.         public boolean containsKey(Object key)   {return m.containsKey(key);}  
  839.         public boolean containsValue(Object val) {return m.containsValue(val);}  
  840.         public V get(Object key)             {return m.get(key);}  
  841.       
  842.         public V put(K key, V value) {  
  843.             throw new UnsupportedOperationException();  
  844.         }  
  845.         public V remove(Object key) {  
  846.             throw new UnsupportedOperationException();  
  847.         }  
  848.         public void putAll(Map<? extends K, ? extends V> m) {  
  849.             throw new UnsupportedOperationException();  
  850.         }  
  851.         public void clear() {  
  852.             throw new UnsupportedOperationException();  
  853.         }  
  854.       
  855.         private transient Set<K> keySet = null;  
  856.         private transient Set<Map.Entry<K,V>> entrySet = null;  
  857.         private transient Collection<V> values = null;  
  858.       
  859.         //返回的key集也是不可修改的  
  860.         public Set<K> keySet() {  
  861.             if (keySet==null)  
  862.                 keySet = unmodifiableSet(m.keySet());  
  863.             return keySet;  
  864.         }  
  865.       
  866.         //EntrySet被重新进行包装  
  867.         public Set<Map.Entry<K,V>> entrySet() {  
  868.             if (entrySet==null)  
  869.                 entrySet = new UnmodifiableEntrySet<K,V>(m.entrySet());  
  870.             return entrySet;  
  871.         }  
  872.       
  873.         public Collection<V> values() {  
  874.             if (values==null)  
  875.                 values = unmodifiableCollection(m.values());  
  876.             return values;  
  877.         }  
  878.   
  879.         public boolean equals(Object o) {return o == this || m.equals(o);}  
  880.         public int hashCode()           {return m.hashCode();}  
  881.         public String toString()        {return m.toString();}  
  882.   
  883.         /** 
  884.          *  
  885.          * 需要重新包装返回的EntrySet对象 
  886.          */  
  887.         static class UnmodifiableEntrySet<K,V> extends UnmodifiableSet<Map.Entry<K,V>> {  
  888.             private static final long serialVersionUID = 7854390611657943733L;  
  889.   
  890.             UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {  
  891.                 super((Set)s);  
  892.             }  
  893.             public Iterator<Map.Entry<K,V>> iterator() {  
  894.                 return new Iterator<Map.Entry<K,V>>() {  
  895.                     //父类UnmodifiableColletion的c  
  896.                     Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();  
  897.   
  898.                     public boolean hasNext() {  
  899.                         return i.hasNext();  
  900.                     }  
  901.                     public Map.Entry<K,V> next() {  
  902.                         return new UnmodifiableEntry<K,V>(i.next());  
  903.                     }  
  904.                     public void remove() {  
  905.                         throw new UnsupportedOperationException();  
  906.                     }  
  907.                 };  
  908.             }  
  909.   
  910.             public Object[] toArray() {  
  911.                 Object[] a = c.toArray();  
  912.                 for (int i=0; i<a.length; i++)  
  913.                     a[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)a[i]);  
  914.                 return a;  
  915.             }  
  916.   
  917.             public <T> T[] toArray(T[] a) {  
  918.                  
  919.                 Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));  
  920.   
  921.                 for (int i=0; i<arr.length; i++)  
  922.                     arr[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)arr[i]);  
  923.   
  924.                 if (arr.length > a.length)  
  925.                     return (T[])arr;  
  926.   
  927.                 System.arraycopy(arr, 0, a, 0, arr.length);  
  928.                 if (a.length > arr.length)  
  929.                     a[arr.length] = null;  
  930.                 return a;  
  931.             }  
  932.   
  933.   
  934.             public boolean contains(Object o) {  
  935.                 if (!(o instanceof Map.Entry))  
  936.                     return false;  
  937.                 return c.contains(new UnmodifiableEntry<K,V>((Map.Entry<K,V>) o));  
  938.             }  
  939.   
  940.             public boolean containsAll(Collection<?> coll) {  
  941.                 Iterator<?> e = coll.iterator();  
  942.                 while (e.hasNext())  
  943.                     if (!contains(e.next())) // Invokes safe contains() above  
  944.                         return false;  
  945.                 return true;  
  946.             }  
  947.             public boolean equals(Object o) {  
  948.                 if (o == this)  
  949.                     return true;  
  950.   
  951.                 if (!(o instanceof Set))  
  952.                     return false;  
  953.                 Set s = (Set) o;  
  954.                 if (s.size() != c.size())  
  955.                     return false;  
  956.                 return containsAll(s); // Invokes safe containsAll() above  
  957.             }  
  958.   
  959.             /** 
  960.              * 重新包装Entry。 
  961.              */  
  962.             private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {  
  963.                 private Map.Entry<? extends K, ? extends V> e;  
  964.   
  965.                 UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;}  
  966.   
  967.                 public K getKey()     {return e.getKey();}  
  968.                 public V getValue()  {return e.getValue();}  
  969.                 public V setValue(V value) {    //调用set方法将抛出一个异常  
  970.                     throw new UnsupportedOperationException();  
  971.                 }  
  972.                 public int hashCode()     {return e.hashCode();}  
  973.                 public boolean equals(Object o) {  
  974.                     if (!(o instanceof Map.Entry))  
  975.                         return false;  
  976.                     Map.Entry t = (Map.Entry)o;  
  977.                     return eq(e.getKey(),   t.getKey()) &&  
  978.                            eq(e.getValue(), t.getValue());  
  979.                 }  
  980.                 public String toString()  {return e.toString();}  
  981.             }  
  982.         }  
  983.     }  
  984.   
  985.     /** 
  986.      * 返回一个不可修改的SortedMap 
  987.      */  
  988.     public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {  
  989.         return new UnmodifiableSortedMap<K,V>(m);  
  990.     }  
  991.   
  992.   
  993.     static class UnmodifiableSortedMap<K,V> extends UnmodifiableMap<K,V>  
  994.       implements SortedMap<K,V>, Serializable {  
  995.         private static final long serialVersionUID = -8806743815996713206L;  
  996.   
  997.         private final SortedMap<K, ? extends V> sm;  
  998.   
  999.         UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}  
  1000.   
  1001.         public Comparator<? super K> comparator() {return sm.comparator();}  
  1002.   
  1003.         public SortedMap<K,V> subMap(K fromKey, K toKey) {  
  1004.             return new UnmodifiableSortedMap<K,V>(sm.subMap(fromKey, toKey));  
  1005.         }  
  1006.         public SortedMap<K,V> headMap(K toKey) {  
  1007.             return new UnmodifiableSortedMap<K,V>(sm.headMap(toKey));  
  1008.         }  
  1009.         public SortedMap<K,V> tailMap(K fromKey) {  
  1010.             return new UnmodifiableSortedMap<K,V>(sm.tailMap(fromKey));  
  1011.         }  
  1012.   
  1013.         public K firstKey()           {return sm.firstKey();}  
  1014.         public K lastKey()            {return sm.lastKey();}  
  1015.     }  
  1016.   
  1017.   
  1018.     // 同步包装  
  1019.   
  1020.     /** 
  1021.      *  
  1022.      * 返回一个线程安全的集合 
  1023.      * 但是当用户遍历此集合时,需要手动进行同步 
  1024.      *  Collection c = Collections.synchronizedCollection(myCollection); 
  1025.      *     ... 
  1026.      *  synchronized(c) { 
  1027.      *      Iterator i = c.iterator(); // Must be in the synchronized block 
  1028.      *      while (i.hasNext()) 
  1029.      *         foo(i.next()); 
  1030.      *  } 
  1031.      *  
  1032.      */  
  1033.     public static <T> Collection<T> synchronizedCollection(Collection<T> c) {  
  1034.         return new SynchronizedCollection<T>(c);  
  1035.     }  
  1036.   
  1037.     static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {  
  1038.         return new SynchronizedCollection<T>(c, mutex);  
  1039.     }  
  1040.   
  1041.     /** 
  1042.      * @serial include 
  1043.      */  
  1044.     static class SynchronizedCollection<E> implements Collection<E>, Serializable {  
  1045.     // use serialVersionUID from JDK 1.2.2 for interoperability  
  1046.         private static final long serialVersionUID = 3053995032091335093L;  
  1047.       
  1048.         final Collection<E> c;  // 返回的集合  
  1049.         final Object mutex;     // 需要同步的对象  
  1050.       
  1051.         SynchronizedCollection(Collection<E> c) {  
  1052.             if (c==null)  
  1053.                  throw new NullPointerException();  
  1054.             this.c = c;  
  1055.             mutex = this;  
  1056.         }  
  1057.         SynchronizedCollection(Collection<E> c, Object mutex) {  
  1058.             this.c = c;  
  1059.             this.mutex = mutex;  
  1060.          }  
  1061.   
  1062.     public int size() {  
  1063.         synchronized(mutex) {return c.size();}  
  1064.         }  
  1065.     public boolean isEmpty() {  
  1066.         synchronized(mutex) {return c.isEmpty();}  
  1067.         }  
  1068.     public boolean contains(Object o) {  
  1069.         synchronized(mutex) {return c.contains(o);}  
  1070.         }  
  1071.     public Object[] toArray() {  
  1072.         synchronized(mutex) {return c.toArray();}  
  1073.         }  
  1074.     public <T> T[] toArray(T[] a) {  
  1075.         synchronized(mutex) {return c.toArray(a);}  
  1076.         }  
  1077.   
  1078.     public Iterator<E> iterator() {  
  1079.             return c.iterator(); // 必须用户自己手动同步  
  1080.         }  
  1081.   
  1082.     public boolean add(E e) {  
  1083.         synchronized(mutex) {return c.add(e);}  
  1084.         }  
  1085.     public boolean remove(Object o) {  
  1086.         synchronized(mutex) {return c.remove(o);}  
  1087.         }  
  1088.   
  1089.     public boolean containsAll(Collection<?> coll) {  
  1090.         synchronized(mutex) {return c.containsAll(coll);}  
  1091.         }  
  1092.     public boolean addAll(Collection<? extends E> coll) {  
  1093.         synchronized(mutex) {return c.addAll(coll);}  
  1094.         }  
  1095.     public boolean removeAll(Collection<?> coll) {  
  1096.         synchronized(mutex) {return c.removeAll(coll);}  
  1097.         }  
  1098.     public boolean retainAll(Collection<?> coll) {  
  1099.         synchronized(mutex) {return c.retainAll(coll);}  
  1100.         }  
  1101.     public void clear() {  
  1102.         synchronized(mutex) {c.clear();}  
  1103.         }  
  1104.     public String toString() {  
  1105.         synchronized(mutex) {return c.toString();}  
  1106.         }  
  1107.         private void writeObject(ObjectOutputStream s) throws IOException {  
  1108.         synchronized(mutex) {s.defaultWriteObject();}  
  1109.         }  
  1110.     }  
  1111.   
  1112.     /** 
  1113.      * 返回一个线程安全的Set 
  1114.      */  
  1115.     public static <T> Set<T> synchronizedSet(Set<T> s) {  
  1116.         return new SynchronizedSet<T>(s);  
  1117.     }  
  1118.   
  1119.     static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {  
  1120.         return new SynchronizedSet<T>(s, mutex);  
  1121.     }  
  1122.   
  1123.     /** 
  1124.      * @serial include 
  1125.      */  
  1126.     static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> {  
  1127.         private static final long serialVersionUID = 487447009682186044L;  
  1128.   
  1129.         SynchronizedSet(Set<E> s) {  
  1130.                 super(s);  
  1131.         }  
  1132.         SynchronizedSet(Set<E> s, Object mutex) {  
  1133.                 super(s, mutex);  
  1134.         }  
  1135.   
  1136.         public boolean equals(Object o) {  
  1137.             synchronized(mutex) {return c.equals(o);}  
  1138.         }  
  1139.         public int hashCode() {  
  1140.             synchronized(mutex) {return c.hashCode();}  
  1141.         }  
  1142.     }  
  1143.   
  1144.     /** 
  1145.      * 返回一个线程安全的SortedSet 
  1146.      */  
  1147.     public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {  
  1148.         return new SynchronizedSortedSet<T>(s);  
  1149.     }  
  1150.   
  1151.     /** 
  1152.      * @serial include 
  1153.      */  
  1154.     static class SynchronizedSortedSet<E> extends SynchronizedSet<E>implements SortedSet<E>{  
  1155.         private static final long serialVersionUID = 8695801310862127406L;  
  1156.   
  1157.         final private SortedSet<E> ss;  
  1158.   
  1159.         SynchronizedSortedSet(SortedSet<E> s) {  
  1160.             super(s);  
  1161.             ss = s;  
  1162.         }  
  1163.         SynchronizedSortedSet(SortedSet<E> s, Object mutex) {  
  1164.             super(s, mutex);  
  1165.             ss = s;  
  1166.         }  
  1167.   
  1168.         public Comparator<? super E> comparator() {  
  1169.             synchronized(mutex) {return ss.comparator();}  
  1170.         }  
  1171.   
  1172.         public SortedSet<E> subSet(E fromElement, E toElement) {  
  1173.         synchronized(mutex) {  
  1174.                 return new SynchronizedSortedSet<E>(  
  1175.                     ss.subSet(fromElement, toElement), mutex);  
  1176.             }  
  1177.         }  
  1178.         public SortedSet<E> headSet(E toElement) {  
  1179.             synchronized(mutex) {  
  1180.                 return new SynchronizedSortedSet<E>(ss.headSet(toElement), mutex);  
  1181.             }  
  1182.         }  
  1183.         public SortedSet<E> tailSet(E fromElement) {  
  1184.             synchronized(mutex) {  
  1185.                return new SynchronizedSortedSet<E>(ss.tailSet(fromElement),mutex);  
  1186.             }  
  1187.         }  
  1188.   
  1189.         public E first() {  
  1190.             synchronized(mutex) {return ss.first();}  
  1191.         }  
  1192.         public E last() {  
  1193.             synchronized(mutex) {return ss.last();}  
  1194.         }  
  1195.     }  
  1196.   
  1197.     /** 
  1198.      * 返回一个线程安全的List, 
  1199.      * 如果List是基于随机访问的,返回的List同样实现了RandomAccess接口 
  1200.      */  
  1201.     public static <T> List<T> synchronizedList(List<T> list) {  
  1202.         return (list instanceof RandomAccess ?  
  1203.                 new SynchronizedRandomAccessList<T>(list) :  
  1204.                 new SynchronizedList<T>(list));  
  1205.     }  
  1206.   
  1207.     static <T> List<T> synchronizedList(List<T> list, Object mutex) {  
  1208.         return (list instanceof RandomAccess ?  
  1209.                 new SynchronizedRandomAccessList<T>(list, mutex) :  
  1210.                 new SynchronizedList<T>(list, mutex));  
  1211.     }  
  1212.   
  1213.     /** 
  1214.      * @serial include 
  1215.      */  
  1216.     static class SynchronizedList<E>extends SynchronizedCollection<E> implements List<E> {  
  1217.         static final long serialVersionUID = -7754090372962971524L;  
  1218.   
  1219.         final List<E> list;  
  1220.   
  1221.         SynchronizedList(List<E> list) {  
  1222.             super(list);  
  1223.             this.list = list;  
  1224.         }  
  1225.         SynchronizedList(List<E> list, Object mutex) {  
  1226.             super(list, mutex);  
  1227.             this.list = list;  
  1228.         }  
  1229.   
  1230.         public boolean equals(Object o) {  
  1231.             synchronized(mutex) {return list.equals(o);}  
  1232.         }  
  1233.         public int hashCode() {  
  1234.             synchronized(mutex) {return list.hashCode();}  
  1235.         }  
  1236.   
  1237.         public E get(int index) {  
  1238.             synchronized(mutex) {return list.get(index);}  
  1239.         }  
  1240.         public E set(int index, E element) {  
  1241.             synchronized(mutex) {return list.set(index, element);}  
  1242.         }  
  1243.         public void add(int index, E element) {  
  1244.             synchronized(mutex) {list.add(index, element);}  
  1245.         }  
  1246.         public E remove(int index) {  
  1247.             synchronized(mutex) {return list.remove(index);}  
  1248.         }  
  1249.   
  1250.         public int indexOf(Object o) {  
  1251.             synchronized(mutex) {return list.indexOf(o);}  
  1252.         }  
  1253.         public int lastIndexOf(Object o) {  
  1254.             synchronized(mutex) {return list.lastIndexOf(o);}  
  1255.         }  
  1256.   
  1257.         public boolean addAll(int index, Collection<? extends E> c) {  
  1258.             synchronized(mutex) {return list.addAll(index, c);}  
  1259.         }  
  1260.   
  1261.         public ListIterator<E> listIterator() {  
  1262.             return list.listIterator(); // Must be manually synched by user  
  1263.         }  
  1264.   
  1265.         public ListIterator<E> listIterator(int index) {  
  1266.             return list.listIterator(index); // Must be manually synched by user  
  1267.         }  
  1268.   
  1269.         public List<E> subList(int fromIndex, int toIndex) {  
  1270.             synchronized(mutex) {  
  1271.                 return new SynchronizedList<E>(list.subList(fromIndex, toIndex),  
  1272.                                             mutex);  
  1273.             }  
  1274.         }  
  1275.   
  1276.   
  1277.         private Object readResolve() {  
  1278.             return (list instanceof RandomAccess  
  1279.             ? new SynchronizedRandomAccessList<E>(list)  
  1280.             : this);  
  1281.         }  
  1282.     }  
  1283.   
  1284.     /** 
  1285.      * @serial include 
  1286.      */  
  1287.     static class SynchronizedRandomAccessList<E>extends SynchronizedList<E>  
  1288.     implements RandomAccess {  
  1289.   
  1290.         SynchronizedRandomAccessList(List<E> list) {  
  1291.             super(list);  
  1292.         }  
  1293.   
  1294.         SynchronizedRandomAccessList(List<E> list, Object mutex) {  
  1295.             super(list, mutex);  
  1296.         }  
  1297.   
  1298.         public List<E> subList(int fromIndex, int toIndex) {  
  1299.             synchronized(mutex) {  
  1300.                 return new SynchronizedRandomAccessList<E>(  
  1301.                     list.subList(fromIndex, toIndex), mutex);  
  1302.             }  
  1303.         }  
  1304.   
  1305.         static final long serialVersionUID = 1530674583602358482L;  
  1306.   
  1307.         private Object writeReplace() {  
  1308.             return new SynchronizedList<E>(list);  
  1309.         }  
  1310.     }  
  1311.   
  1312.     /** 
  1313.      * 返回一个线程安全的map 
  1314.      */  
  1315.     public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {  
  1316.     return new SynchronizedMap<K,V>(m);  
  1317.     }  
  1318.   
  1319.     /** 
  1320.      * @serial include 
  1321.      */  
  1322.     private static class SynchronizedMap<K,V>  
  1323.     implements Map<K,V>, Serializable {  
  1324.     // use serialVersionUID from JDK 1.2.2 for interoperability  
  1325.     private static final long serialVersionUID = 1978198479659022715L;  
  1326.   
  1327.     private final Map<K,V> m;     // Backing Map  
  1328.         final Object      mutex;    // Object on which to synchronize  
  1329.   
  1330.     SynchronizedMap(Map<K,V> m) {  
  1331.             if (m==null)  
  1332.                 throw new NullPointerException();  
  1333.             this.m = m;  
  1334.             mutex = this;  
  1335.         }  
  1336.   
  1337.     SynchronizedMap(Map<K,V> m, Object mutex) {  
  1338.             this.m = m;  
  1339.             this.mutex = mutex;  
  1340.         }  
  1341.   
  1342.     public int size() {  
  1343.         synchronized(mutex) {return m.size();}  
  1344.         }  
  1345.     public boolean isEmpty(){  
  1346.         synchronized(mutex) {return m.isEmpty();}  
  1347.         }  
  1348.     public boolean containsKey(Object key) {  
  1349.         synchronized(mutex) {return m.containsKey(key);}  
  1350.         }  
  1351.     public boolean containsValue(Object value){  
  1352.         synchronized(mutex) {return m.containsValue(value);}  
  1353.         }  
  1354.     public V get(Object key) {  
  1355.         synchronized(mutex) {return m.get(key);}  
  1356.         }  
  1357.   
  1358.     public V put(K key, V value) {  
  1359.         synchronized(mutex) {return m.put(key, value);}  
  1360.         }  
  1361.     public V remove(Object key) {  
  1362.         synchronized(mutex) {return m.remove(key);}  
  1363.         }  
  1364.     public void putAll(Map<? extends K, ? extends V> map) {  
  1365.         synchronized(mutex) {m.putAll(map);}  
  1366.         }  
  1367.     public void clear() {  
  1368.         synchronized(mutex) {m.clear();}  
  1369.     }  
  1370.   
  1371.     private transient Set<K> keySet = null;  
  1372.     private transient Set<Map.Entry<K,V>> entrySet = null;  
  1373.     private transient Collection<V> values = null;  
  1374.   
  1375.     public Set<K> keySet() {  
  1376.             synchronized(mutex) {  
  1377.                 if (keySet==null)  
  1378.                     keySet = new SynchronizedSet<K>(m.keySet(), mutex);  
  1379.                 return keySet;  
  1380.             }  
  1381.     }  
  1382.   
  1383.     public Set<Map.Entry<K,V>> entrySet() {  
  1384.             synchronized(mutex) {  
  1385.                 if (entrySet==null)  
  1386.                     entrySet = new SynchronizedSet<Map.Entry<K,V>>(m.entrySet(), mutex);  
  1387.                 return entrySet;  
  1388.             }  
  1389.     }  
  1390.   
  1391.     public Collection<V> values() {  
  1392.             synchronized(mutex) {  
  1393.                 if (values==null)  
  1394.                     values = new SynchronizedCollection<V>(m.values(), mutex);  
  1395.                 return values;  
  1396.             }  
  1397.         }  
  1398.   
  1399.     public boolean equals(Object o) {  
  1400.             synchronized(mutex) {return m.equals(o);}  
  1401.         }  
  1402.     public int hashCode() {  
  1403.             synchronized(mutex) {return m.hashCode();}  
  1404.         }  
  1405.     public String toString() {  
  1406.         synchronized(mutex) {return m.toString();}  
  1407.         }  
  1408.         private void writeObject(ObjectOutputStream s) throws IOException {  
  1409.         synchronized(mutex) {s.defaultWriteObject();}  
  1410.         }  
  1411.     }  
  1412.   
  1413.     /** 
  1414.      * 返回一个线程安全的SortedSet 
  1415.      */  
  1416.     public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {  
  1417.     return new SynchronizedSortedMap<K,V>(m);  
  1418.     }  
  1419.   
  1420.   
  1421.     /** 
  1422.      * @serial include 
  1423.      */  
  1424.     static class SynchronizedSortedMap<K,V>  
  1425.     extends SynchronizedMap<K,V>  
  1426.     implements SortedMap<K,V>  
  1427.     {  
  1428.     private static final long serialVersionUID = -8798146769416483793L;  
  1429.   
  1430.         private final SortedMap<K,V> sm;  
  1431.   
  1432.     SynchronizedSortedMap(SortedMap<K,V> m) {  
  1433.             super(m);  
  1434.             sm = m;  
  1435.         }  
  1436.     SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {  
  1437.             super(m, mutex);  
  1438.             sm = m;  
  1439.         }  
  1440.   
  1441.     public Comparator<? super K> comparator() {  
  1442.         synchronized(mutex) {return sm.comparator();}  
  1443.         }  
  1444.   
  1445.         public SortedMap<K,V> subMap(K fromKey, K toKey) {  
  1446.         synchronized(mutex) {  
  1447.                 return new SynchronizedSortedMap<K,V>(  
  1448.                     sm.subMap(fromKey, toKey), mutex);  
  1449.             }  
  1450.         }  
  1451.         public SortedMap<K,V> headMap(K toKey) {  
  1452.         synchronized(mutex) {  
  1453.                 return new SynchronizedSortedMap<K,V>(sm.headMap(toKey), mutex);  
  1454.             }  
  1455.         }  
  1456.         public SortedMap<K,V> tailMap(K fromKey) {  
  1457.         synchronized(mutex) {  
  1458.                return new SynchronizedSortedMap<K,V>(sm.tailMap(fromKey),mutex);  
  1459.             }  
  1460.         }  
  1461.   
  1462.         public K firstKey() {  
  1463.         synchronized(mutex) {return sm.firstKey();}  
  1464.         }  
  1465.         public K lastKey() {  
  1466.         synchronized(mutex) {return sm.lastKey();}  
  1467.         }  
  1468.     }  
  1469.   
  1470.     // Dynamically typesafe collection wrappers  
  1471.   
  1472.     /** 
  1473.      *  
  1474.      * 返回一个动态的类型安全的集合。任何试图插入错误类型的元素的操作将立刻抛出 
  1475.      * ClassCastException 
  1476.      * 动态类型安全视图的一个主要作用是用作debug调试, 
  1477.      * 因为它能正确反映出出错的位置。 
  1478.      * 例如:ArrayList<String> strings = new ArrayList<String>(); 
  1479.      * ArrayList rawList = strings; 
  1480.      * rawList.add(new Date()); 
  1481.      * add方法并不进行类型检查,所以存入了非String的对象。只有在重新获取该对象 
  1482.      * 转化为String类型的时候才抛出异常。 
  1483.      * 而动态类型安全的集合能在add时就会抛出ClassCastException。 
  1484.      * 这种方法的优点是错误可以在正确的位置被报告 
  1485.      *  
  1486.      * 
  1487.      */  
  1488.     public static <E> Collection<E> checkedCollection(Collection<E> c,Class<E> type) {  
  1489.         return new CheckedCollection<E>(c, type);  
  1490.     }  
  1491.   
  1492.     /** 
  1493.      * @serial include 
  1494.      */  
  1495.     static class CheckedCollection<E> implements Collection<E>, Serializable {  
  1496.         private static final long serialVersionUID = 1578914078182001775L;  
  1497.   
  1498.         final Collection<E> c;  
  1499.         final Class<E> type;  
  1500.   
  1501.         void typeCheck(Object o) {  
  1502.             if (!type.isInstance(o))    //o是否能被转换成type类型  
  1503.                 throw new ClassCastException("Attempt to insert " +  
  1504.                    o.getClass() + " element into collection with element type "  
  1505.                    + type);  
  1506.         }  
  1507.   
  1508.         CheckedCollection(Collection<E> c, Class<E> type) {  
  1509.             if (c==null || type == null)  
  1510.                 throw new NullPointerException();  
  1511.             this.c = c;  
  1512.             this.type = type;  
  1513.         }  
  1514.   
  1515.         public int size()                   { return c.size(); }  
  1516.         public boolean isEmpty()            { return c.isEmpty(); }  
  1517.         public boolean contains(Object o)   { return c.contains(o); }  
  1518.         public Object[] toArray()           { return c.toArray(); }  
  1519.         public <T> T[] toArray(T[] a)       { return c.toArray(a); }  
  1520.         public String toString()            { return c.toString(); }  
  1521.         public boolean remove(Object o)     { return c.remove(o); }  
  1522.         public boolean containsAll(Collection<?> coll) {  
  1523.             return c.containsAll(coll);  
  1524.         }  
  1525.         public boolean removeAll(Collection<?> coll) {  
  1526.             return c.removeAll(coll);  
  1527.         }  
  1528.         public boolean retainAll(Collection<?> coll) {  
  1529.             return c.retainAll(coll);  
  1530.         }  
  1531.         public void clear() {  
  1532.             c.clear();  
  1533.         }  
  1534.   
  1535.         public Iterator<E> iterator() {  
  1536.             return new Iterator<E>() {  
  1537.             private final Iterator<E> it = c.iterator();  
  1538.             public boolean hasNext() { return it.hasNext(); }  
  1539.             public E next()          { return it.next(); }  
  1540.             public void remove()     {        it.remove(); }};  
  1541.         }  
  1542.   
  1543.         public boolean add(E e){  
  1544.             typeCheck(e);   //添加元素需要进行类型检查  
  1545.             return c.add(e);  
  1546.         }  
  1547.   
  1548.         public boolean addAll(Collection<? extends E> coll) {  
  1549.             E[] a = null;  
  1550.             try {  
  1551.                 a = coll.toArray(zeroLengthElementArray()); //根据zero数组的类型来转换集合为数组。如果coll中含有其他类型这里就会抛出异常  
  1552.             } catch (ArrayStoreException e) {  
  1553.                 throw new ClassCastException();  
  1554.             }  
  1555.   
  1556.             boolean result = false;  
  1557.             for (E e : a)  
  1558.                 result |= c.add(e); //只要集合发生了改变就返回true  
  1559.             return result;  
  1560.         }  
  1561.   
  1562.         private E[] zeroLengthElementArray = null// Lazily initialized  
  1563.   
  1564.         /* 
  1565.          * We don't need locking or volatile, because it's OK if we create 
  1566.          * several zeroLengthElementArrays, and they're immutable. 
  1567.          */  
  1568.         E[] zeroLengthElementArray() {  
  1569.             if (zeroLengthElementArray == null)  
  1570.                 zeroLengthElementArray = (E[]) Array.newInstance(type, 0);  
  1571.             return zeroLengthElementArray;  
  1572.         }  
  1573.     }  
  1574.   
  1575.     /** 
  1576.      * 返回一个会检查类型的集合Set 
  1577.      */  
  1578.     public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {  
  1579.         return new CheckedSet<E>(s, type);  
  1580.     }  
  1581.   
  1582.     /** 
  1583.      * @serial include 
  1584.      */  
  1585.     static class CheckedSet<E> extends CheckedCollection<E>  
  1586.                                  implements Set<E>, Serializable{  
  1587.         private static final long serialVersionUID = 4694047833775013803L;  
  1588.   
  1589.         CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }  
  1590.   
  1591.         public boolean equals(Object o) { return o == this || c.equals(o); }  
  1592.         public int hashCode()           { return c.hashCode(); }  
  1593.     }  
  1594.   
  1595.     /** 
  1596.      * 返回一个类型安全的集合SortedSet 
  1597.      */  
  1598.     public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,Class<E> type) {  
  1599.         return new CheckedSortedSet<E>(s, type);  
  1600.     }  
  1601.   
  1602.     /** 
  1603.      * @serial include 
  1604.      */  
  1605.     static class CheckedSortedSet<E> extends CheckedSet<E>  
  1606.         implements SortedSet<E>, Serializable{  
  1607.         private static final long serialVersionUID = 1599911165492914959L;  
  1608.         private final SortedSet<E> ss;  
  1609.   
  1610.         CheckedSortedSet(SortedSet<E> s, Class<E> type) {  
  1611.             super(s, type);  
  1612.             ss = s;  
  1613.         }  
  1614.   
  1615.         public Comparator<? super E> comparator() { return ss.comparator(); }  
  1616.         public E first()                   { return ss.first(); }  
  1617.         public E last()                    { return ss.last(); }  
  1618.   
  1619.         public SortedSet<E> subSet(E fromElement, E toElement) {  
  1620.             return new CheckedSortedSet<E>(ss.subSet(fromElement,toElement),  
  1621.                                            type);  
  1622.         }  
  1623.         public SortedSet<E> headSet(E toElement) {  
  1624.             return new CheckedSortedSet<E>(ss.headSet(toElement), type);  
  1625.         }  
  1626.         public SortedSet<E> tailSet(E fromElement) {  
  1627.             return new CheckedSortedSet<E>(ss.tailSet(fromElement), type);  
  1628.         }  
  1629.     }  
  1630.   
  1631.     /** 
  1632.      * 返回一个类型安全的集合List 
  1633.      */  
  1634.     public static <E> List<E> checkedList(List<E> list, Class<E> type) {  
  1635.         return (list instanceof RandomAccess ?  
  1636.                 new CheckedRandomAccessList<E>(list, type) :  
  1637.                 new CheckedList<E>(list, type));  
  1638.     }  
  1639.   
  1640.     /** 
  1641.      * @serial include 
  1642.      */  
  1643.     static class CheckedList<E> extends CheckedCollection<E>  
  1644.                                 implements List<E>  
  1645.     {  
  1646.         static final long serialVersionUID = 65247728283967356L;  
  1647.         final List<E> list;  
  1648.   
  1649.         CheckedList(List<E> list, Class<E> type) {  
  1650.             super(list, type);  
  1651.             this.list = list;  
  1652.         }  
  1653.   
  1654.         public boolean equals(Object o)  { return o == this || list.equals(o); }  
  1655.         public int hashCode()            { return list.hashCode(); }  
  1656.         public E get(int index)          { return list.get(index); }  
  1657.         public E remove(int index)       { return list.remove(index); }  
  1658.         public int indexOf(Object o)     { return list.indexOf(o); }  
  1659.         public int lastIndexOf(Object o) { return list.lastIndexOf(o); }  
  1660.   
  1661.         public E set(int index, E element) {  
  1662.             typeCheck(element);  
  1663.             return list.set(index, element);  
  1664.         }  
  1665.   
  1666.         public void add(int index, E element) {  
  1667.             typeCheck(element);  
  1668.             list.add(index, element);  
  1669.         }  
  1670.   
  1671.         public boolean addAll(int index, Collection<? extends E> c) {  
  1672.             // See CheckCollection.addAll, above, for an explanation  
  1673.             E[] a = null;  
  1674.             try {  
  1675.                 a = c.toArray(zeroLengthElementArray());  
  1676.             } catch (ArrayStoreException e) {  
  1677.                 throw new ClassCastException();  
  1678.             }  
  1679.   
  1680.             return list.addAll(index, Arrays.asList(a));  
  1681.         }  
  1682.         public ListIterator<E> listIterator()   { return listIterator(0); }  
  1683.   
  1684.         public ListIterator<E> listIterator(final int index) {  
  1685.             return new ListIterator<E>() {  
  1686.                 ListIterator<E> i = list.listIterator(index);  
  1687.   
  1688.                 public boolean hasNext()     { return i.hasNext(); }  
  1689.                 public E next()              { return i.next(); }  
  1690.                 public boolean hasPrevious() { return i.hasPrevious(); }  
  1691.                 public E previous()          { return i.previous(); }  
  1692.                 public int nextIndex()       { return i.nextIndex(); }  
  1693.                 public int previousIndex()   { return i.previousIndex(); }  
  1694.                 public void remove()         { i.remove(); }  
  1695.   
  1696.                 public void set(E e) {  
  1697.                     typeCheck(e);  
  1698.                     i.set(e);  
  1699.                 }  
  1700.   
  1701.                 public void add(E e) {  
  1702.                     typeCheck(e);  
  1703.                     i.add(e);  
  1704.                 }  
  1705.             };  
  1706.         }  
  1707.   
  1708.         public List<E> subList(int fromIndex, int toIndex) {  
  1709.             return new CheckedList<E>(list.subList(fromIndex, toIndex), type);  
  1710.         }  
  1711.     }  
  1712.   
  1713.     /** 
  1714.      * @serial include 
  1715.      */  
  1716.     static class CheckedRandomAccessList<E> extends CheckedList<E>  
  1717.                                             implements RandomAccess  
  1718.     {  
  1719.         private static final long serialVersionUID = 1638200125423088369L;  
  1720.   
  1721.         CheckedRandomAccessList(List<E> list, Class<E> type) {  
  1722.             super(list, type);  
  1723.         }  
  1724.   
  1725.         public List<E> subList(int fromIndex, int toIndex) {  
  1726.             return new CheckedRandomAccessList<E>(  
  1727.                 list.subList(fromIndex, toIndex), type);  
  1728.         }  
  1729.     }  
  1730.   
  1731.     /** 
  1732.      * 返回一个类型安全的集合Map 
  1733.      */  
  1734.     public static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType,  
  1735.                                               Class<V> valueType) {  
  1736.         return new CheckedMap<K,V>(m, keyType, valueType);  
  1737.     }  
  1738.   
  1739.   
  1740.     /** 
  1741.      * @serial include 
  1742.      */  
  1743.     private static class CheckedMap<K,V> implements Map<K,V>,  
  1744.                                                          Serializable  
  1745.     {  
  1746.         private static final long serialVersionUID = 5742860141034234728L;  
  1747.   
  1748.         private final Map<K, V> m;  
  1749.         final Class<K> keyType;  
  1750.         final Class<V> valueType;  
  1751.   
  1752.         //需要对key与value都进行类型检查  
  1753.         private void typeCheck(Object key, Object value) {  
  1754.             if (!keyType.isInstance(key))  
  1755.                 throw new ClassCastException("Attempt to insert " +  
  1756.                     key.getClass() + " key into collection with key type "  
  1757.                     + keyType);  
  1758.   
  1759.             if (!valueType.isInstance(value))  
  1760.                 throw new ClassCastException("Attempt to insert " +  
  1761.                     value.getClass() +" value into collection with value type "  
  1762.                     + valueType);  
  1763.         }  
  1764.   
  1765.         CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {  
  1766.             if (m == null || keyType == null || valueType == null)  
  1767.                 throw new NullPointerException();  
  1768.             this.m = m;  
  1769.             this.keyType = keyType;  
  1770.             this.valueType = valueType;  
  1771.         }  
  1772.   
  1773.         public int size()                      { return m.size(); }  
  1774.         public boolean isEmpty()               { return m.isEmpty(); }  
  1775.         public boolean containsKey(Object key) { return m.containsKey(key); }  
  1776.         public boolean containsValue(Object v) { return m.containsValue(v); }  
  1777.         public V get(Object key)               { return m.get(key); }  
  1778.         public V remove(Object key)            { return m.remove(key); }  
  1779.         public void clear()                    { m.clear(); }  
  1780.         public Set<K> keySet()                 { return m.keySet(); }  
  1781.         public Collection<V> values()          { return m.values(); }  
  1782.         public boolean equals(Object o)        { return o == this || m.equals(o); }  
  1783.         public int hashCode()                  { return m.hashCode(); }  
  1784.         public String toString()               { return m.toString(); }  
  1785.   
  1786.         public V put(K key, V value) {  
  1787.             typeCheck(key, value);  
  1788.             return m.put(key, value);  
  1789.         }  
  1790.   
  1791.         public void putAll(Map<? extends K, ? extends V> t) {  
  1792.             // See CheckCollection.addAll, above, for an explanation  
  1793.             K[] keys = null;  
  1794.             try {  
  1795.                 keys = t.keySet().toArray(zeroLengthKeyArray());  
  1796.             } catch (ArrayStoreException e) {  
  1797.                 throw new ClassCastException();  
  1798.             }  
  1799.             V[] values = null;  
  1800.             try {  
  1801.                 values = t.values().toArray(zeroLengthValueArray());  
  1802.             } catch (ArrayStoreException e) {  
  1803.                 throw new ClassCastException();  
  1804.             }  
  1805.   
  1806.             if (keys.length != values.length)  
  1807.                 throw new ConcurrentModificationException();  
  1808.   
  1809.             for (int i = 0; i < keys.length; i++)  
  1810.                 m.put(keys[i], values[i]);  
  1811.         }  
  1812.   
  1813.         // Lazily initialized  
  1814.         private K[] zeroLengthKeyArray   = null;  
  1815.         private V[] zeroLengthValueArray = null;  
  1816.   
  1817.         /* 
  1818.          * We don't need locking or volatile, because it's OK if we create 
  1819.          * several zeroLengthValueArrays, and they're immutable. 
  1820.          */  
  1821.         private K[] zeroLengthKeyArray() {  
  1822.             if (zeroLengthKeyArray == null)  
  1823.                 zeroLengthKeyArray = (K[]) Array.newInstance(keyType, 0);  
  1824.             return zeroLengthKeyArray;  
  1825.         }  
  1826.         private V[] zeroLengthValueArray() {  
  1827.             if (zeroLengthValueArray == null)  
  1828.                 zeroLengthValueArray = (V[]) Array.newInstance(valueType, 0);  
  1829.             return zeroLengthValueArray;  
  1830.         }  
  1831.   
  1832.         private transient Set<Map.Entry<K,V>> entrySet = null;  
  1833.   
  1834.         public Set<Map.Entry<K,V>> entrySet() {  
  1835.             if (entrySet==null)  
  1836.                 entrySet = new CheckedEntrySet<K,V>(m.entrySet(), valueType);  
  1837.             return entrySet;  
  1838.         }  
  1839.   
  1840.         /** 
  1841.          * We need this class in addition to CheckedSet as Map.Entry permits 
  1842.          * modification of the backing Map via the setValue operation.  This 
  1843.          * class is subtle: there are many possible attacks that must be 
  1844.          * thwarted. 
  1845.          * 
  1846.          * @serial exclude 
  1847.          */  
  1848.         static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {  
  1849.             Set<Map.Entry<K,V>> s;  
  1850.             Class<V> valueType;  
  1851.   
  1852.             CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {  
  1853.                 this.s = s;  
  1854.                 this.valueType = valueType;  
  1855.             }  
  1856.   
  1857.             public int size()                   { return s.size(); }  
  1858.             public boolean isEmpty()            { return s.isEmpty(); }  
  1859.             public String toString()            { return s.toString(); }  
  1860.             public int hashCode()               { return s.hashCode(); }  
  1861.             public boolean remove(Object o)     { return s.remove(o); }  
  1862.             public boolean removeAll(Collection<?> coll) {  
  1863.                 return s.removeAll(coll);  
  1864.             }  
  1865.             public boolean retainAll(Collection<?> coll) {  
  1866.                 return s.retainAll(coll);  
  1867.             }  
  1868.             public void clear() {  
  1869.                 s.clear();  
  1870.             }  
  1871.   
  1872.             public boolean add(Map.Entry<K, V> e){  
  1873.                 throw new UnsupportedOperationException();  
  1874.             }  
  1875.             public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {  
  1876.                 throw new UnsupportedOperationException();  
  1877.             }  
  1878.   
  1879.   
  1880.             public Iterator<Map.Entry<K,V>> iterator() {  
  1881.                 return new Iterator<Map.Entry<K,V>>() {  
  1882.                     Iterator<Map.Entry<K, V>> i = s.iterator();  
  1883.   
  1884.                     public boolean hasNext() { return i.hasNext(); }  
  1885.                     public void remove()     { i.remove(); }  
  1886.   
  1887.                     public Map.Entry<K,V> next() {  
  1888.                         return new CheckedEntry<K,V>(i.next(), valueType);  
  1889.                     }  
  1890.                 };  
  1891.             }  
  1892.   
  1893.             public Object[] toArray() {  
  1894.                 Object[] source = s.toArray();  
  1895.   
  1896.                 /* 
  1897.                  * Ensure that we don't get an ArrayStoreException even if 
  1898.                  * s.toArray returns an array of something other than Object 
  1899.                  */  
  1900.                 Object[] dest = (CheckedEntry.class.isInstance(  
  1901.                     source.getClass().getComponentType()) ? source :  
  1902.                                  new Object[source.length]);  
  1903.   
  1904.                 for (int i = 0; i < source.length; i++)  
  1905.                     dest[i] = new CheckedEntry<K,V>((Map.Entry<K,V>)source[i],  
  1906.                                                     valueType);  
  1907.                 return dest;  
  1908.             }  
  1909.   
  1910.             public <T> T[] toArray(T[] a) {  
  1911.                 // We don't pass a to s.toArray, to avoid window of  
  1912.                 // vulnerability wherein an unscrupulous multithreaded client  
  1913.                 // could get his hands on raw (unwrapped) Entries from s.  
  1914.                 Object[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));  
  1915.   
  1916.                 for (int i=0; i<arr.length; i++)  
  1917.                     arr[i] = new CheckedEntry<K,V>((Map.Entry<K,V>)arr[i],  
  1918.                                                    valueType);  
  1919.                 if (arr.length > a.length)  
  1920.                     return (T[])arr;  
  1921.   
  1922.                 System.arraycopy(arr, 0, a, 0, arr.length);  
  1923.                 if (a.length > arr.length)  
  1924.                     a[arr.length] = null;  
  1925.                 return a;  
  1926.             }  
  1927.   
  1928.             /** 
  1929.              * This method is overridden to protect the backing set against 
  1930.              * an object with a nefarious equals function that senses 
  1931.              * that the equality-candidate is Map.Entry and calls its 
  1932.              * setValue method. 
  1933.              */  
  1934.             public boolean contains(Object o) {  
  1935.                 if (!(o instanceof Map.Entry))  
  1936.                     return false;  
  1937.                 return s.contains(  
  1938.                     new CheckedEntry<K,V>((Map.Entry<K,V>) o, valueType));  
  1939.             }  
  1940.   
  1941.             /** 
  1942.              * The next two methods are overridden to protect against 
  1943.              * an unscrupulous collection whose contains(Object o) method 
  1944.              * senses when o is a Map.Entry, and calls o.setValue. 
  1945.              */  
  1946.             public boolean containsAll(Collection<?> coll) {  
  1947.                 Iterator<?> e = coll.iterator();  
  1948.                 while (e.hasNext())  
  1949.                     if (!contains(e.next())) // Invokes safe contains() above  
  1950.                         return false;  
  1951.                 return true;  
  1952.             }  
  1953.   
  1954.             public boolean equals(Object o) {  
  1955.                 if (o == this)  
  1956.                     return true;  
  1957.                 if (!(o instanceof Set))  
  1958.                     return false;  
  1959.                 Set<?> that = (Set<?>) o;  
  1960.                 if (that.size() != s.size())  
  1961.                     return false;  
  1962.                 return containsAll(that); // Invokes safe containsAll() above  
  1963.             }  
  1964.   
  1965.             /** 
  1966.              * This "wrapper class" serves two purposes: it prevents 
  1967.              * the client from modifying the backing Map, by short-circuiting 
  1968.              * the setValue method, and it protects the backing Map against 
  1969.              * an ill-behaved Map.Entry that attempts to modify another 
  1970.              * Map Entry when asked to perform an equality check. 
  1971.              */  
  1972.             private static class CheckedEntry<K,V> implements Map.Entry<K,V> {  
  1973.                 private Map.Entry<K, V> e;  
  1974.                 private Class<V> valueType;  
  1975.   
  1976.                 CheckedEntry(Map.Entry<K, V> e, Class<V> valueType) {  
  1977.                     this.e = e;  
  1978.                     this.valueType = valueType;  
  1979.                 }  
  1980.   
  1981.                 public K getKey()        { return e.getKey(); }  
  1982.                 public V getValue()      { return e.getValue(); }  
  1983.                 public int hashCode()    { return e.hashCode(); }  
  1984.                 public String toString() { return e.toString(); }  
  1985.   
  1986.   
  1987.                 public V setValue(V value) {  
  1988.                     if (!valueType.isInstance(value))  
  1989.                         throw new ClassCastException("Attempt to insert " +  
  1990.                         value.getClass() +  
  1991.                         " value into collection with value type " + valueType);  
  1992.                     return e.setValue(value);  
  1993.                 }  
  1994.   
  1995.                 public boolean equals(Object o) {  
  1996.                     if (!(o instanceof Map.Entry))  
  1997.                         return false;  
  1998.                     Map.Entry t = (Map.Entry)o;  
  1999.                     return eq(e.getKey(),   t.getKey()) &&  
  2000.                            eq(e.getValue(), t.getValue());  
  2001.                 }  
  2002.             }  
  2003.         }  
  2004.     }  
  2005.   
  2006.     /** 
  2007.      * 返回一个类型安全的集合SortedMap 
  2008.      */  
  2009.     public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,  
  2010.                                                         Class<K> keyType,  
  2011.                                                         Class<V> valueType) {  
  2012.         return new CheckedSortedMap<K,V>(m, keyType, valueType);  
  2013.     }  
  2014.   
  2015.     /** 
  2016.      * @serial include 
  2017.      */  
  2018.     static class CheckedSortedMap<K,V> extends CheckedMap<K,V>  
  2019.         implements SortedMap<K,V>, Serializable  
  2020.     {  
  2021.         private static final long serialVersionUID = 1599671320688067438L;  
  2022.   
  2023.         private final SortedMap<K, V> sm;  
  2024.   
  2025.         CheckedSortedMap(SortedMap<K, V> m,  
  2026.                          Class<K> keyType, Class<V> valueType) {  
  2027.             super(m, keyType, valueType);  
  2028.             sm = m;  
  2029.         }  
  2030.   
  2031.         public Comparator<? super K> comparator() { return sm.comparator(); }  
  2032.         public K firstKey()                       { return sm.firstKey(); }  
  2033.         public K lastKey()                        { return sm.lastKey(); }  
  2034.   
  2035.         public SortedMap<K,V> subMap(K fromKey, K toKey) {  
  2036.             return new CheckedSortedMap<K,V>(sm.subMap(fromKey, toKey),  
  2037.                                              keyType, valueType);  
  2038.         }  
  2039.   
  2040.         public SortedMap<K,V> headMap(K toKey) {  
  2041.             return new CheckedSortedMap<K,V>(sm.headMap(toKey),  
  2042.                                              keyType, valueType);  
  2043.         }  
  2044.   
  2045.         public SortedMap<K,V> tailMap(K fromKey) {  
  2046.             return new CheckedSortedMap<K,V>(sm.tailMap(fromKey),  
  2047.                                              keyType, valueType);  
  2048.         }  
  2049.     }  
  2050.   
  2051.     // 其他  
  2052.   
  2053.     /** 
  2054.      * 不可变的空集 
  2055.      */  
  2056.     public static final Set EMPTY_SET = new EmptySet();  
  2057.   
  2058.     /** 
  2059.      * 
  2060.      *  返回一个不可变的空集 
  2061.      *  size始终为0 
  2062.      */  
  2063.     public static final <T> Set<T> emptySet() {  
  2064.     return (Set<T>) EMPTY_SET;  
  2065.     }  
  2066.   
  2067.     /** 
  2068.      * @serial include 
  2069.      */  
  2070.     private static class EmptySet extends AbstractSet<Object> implements Serializable {  
  2071.     // use serialVersionUID from JDK 1.2.2 for interoperability  
  2072.     private static final long serialVersionUID = 1582296315990362920L;  
  2073.   
  2074.         public Iterator<Object> iterator() {  
  2075.             return new Iterator<Object>() {  
  2076.                 public boolean hasNext() {  
  2077.                     return false;  
  2078.                 }  
  2079.                 public Object next() {  
  2080.                     throw new NoSuchElementException();  
  2081.                 }  
  2082.                 public void remove() {  
  2083.                     throw new UnsupportedOperationException();  
  2084.                 }  
  2085.             };  
  2086.         }  
  2087.   
  2088.         public int size() {return 0;}  
  2089.   
  2090.         public boolean contains(Object obj) {return false;}  
  2091.   
  2092.         // Preserves singleton property  
  2093.         private Object readResolve() {  
  2094.             return EMPTY_SET;  
  2095.         }  
  2096.     }  
  2097.   
  2098.    
  2099.     public static final List EMPTY_LIST = new EmptyList();  
  2100.   
  2101.   
  2102.     public static final <T> List<T> emptyList() {  
  2103.     return (List<T>) EMPTY_LIST;  
  2104.     }  
  2105.   
  2106.     /** 
  2107.      * @serial include 
  2108.      */  
  2109.     private static class EmptyList extends AbstractList<Object>  
  2110.     implements RandomAccess, Serializable {  
  2111.     // use serialVersionUID from JDK 1.2.2 for interoperability  
  2112.     private static final long serialVersionUID = 8842843931221139166L;  
  2113.   
  2114.         public int size() {return 0;}  
  2115.   
  2116.         public boolean contains(Object obj) {return false;}  
  2117.   
  2118.         public Object get(int index) {  
  2119.             throw new IndexOutOfBoundsException("Index: "+index);  
  2120.         }  
  2121.   
  2122.         // Preserves singleton property  
  2123.         private Object readResolve() {  
  2124.             return EMPTY_LIST;  
  2125.         }  
  2126.     }  
  2127.   
  2128.   
  2129.     public static final Map EMPTY_MAP = new EmptyMap();  
  2130.   
  2131.    
  2132.     public static final <K,V> Map<K,V> emptyMap() {  
  2133.     return (Map<K,V>) EMPTY_MAP;  
  2134.     }  
  2135.   
  2136.     private static class EmptyMap  
  2137.     extends AbstractMap<Object,Object>  
  2138.     implements Serializable {  
  2139.   
  2140.         private static final long serialVersionUID = 6428348081105594320L;  
  2141.   
  2142.         public int size()                          {return 0;}  
  2143.   
  2144.         public boolean isEmpty()                   {return true;}  
  2145.   
  2146.         public boolean containsKey(Object key)     {return false;}  
  2147.   
  2148.         public boolean containsValue(Object value) {return false;}  
  2149.   
  2150.         public Object get(Object key)              {return null;}  
  2151.   
  2152.         public Set<Object> keySet()                {return Collections.<Object>emptySet();}  
  2153.   
  2154.         public Collection<Object> values()         {return Collections.<Object>emptySet();}  
  2155.   
  2156.         public Set<Map.Entry<Object,Object>> entrySet() {  
  2157.         return Collections.emptySet();  
  2158.     }  
  2159.   
  2160.         public boolean equals(Object o) {  
  2161.             return (o instanceof Map) && ((Map)o).size()==0;  
  2162.         }  
  2163.   
  2164.         public int hashCode()                      {return 0;}  
  2165.   
  2166.         // Preserves singleton property  
  2167.         private Object readResolve() {  
  2168.             return EMPTY_MAP;  
  2169.         }  
  2170.     }  
  2171.   
  2172.     /** 
  2173.      *  
  2174.      * 返回只包含一个元素的不可变的集合 
  2175.      */  
  2176.     public static <T> Set<T> singleton(T o) {  
  2177.     return new SingletonSet<T>(o);  
  2178.     }  
  2179.   
  2180.     /** 
  2181.      * @serial include 
  2182.      */  
  2183.     private static class SingletonSet<E> extends AbstractSet<E>  
  2184.     implements Serializable{  
  2185.     // use serialVersionUID from JDK 1.2.2 for interoperability  
  2186.         private static final long serialVersionUID = 3193687207550431679L;  
  2187.   
  2188.         final private E element;  
  2189.   
  2190.         SingletonSet(E e) {element = e;}  
  2191.   
  2192.         public Iterator<E> iterator() {  
  2193.             return new Iterator<E>() {  
  2194.                 private boolean hasNext = true;  
  2195.                 public boolean hasNext() {  
  2196.                     return hasNext;  
  2197.                 }  
  2198.                 public E next() {  
  2199.                     if (hasNext) {  
  2200.                         hasNext = false;  
  2201.                         return element;  
  2202.                     }  
  2203.                     throw new NoSuchElementException();  
  2204.                 }  
  2205.                 public void remove() {  
  2206.                     throw new UnsupportedOperationException();  
  2207.                 }  
  2208.             };  
  2209.         }  
  2210.   
  2211.         public int size() {return 1;}  
  2212.   
  2213.         public boolean contains(Object o) {return eq(o, element);}  
  2214.     }  
  2215.   
  2216.   
  2217.     public static <T> List<T> singletonList(T o) {  
  2218.     return new SingletonList<T>(o);  
  2219.     }  
  2220.   
  2221.     private static class SingletonList<E>  
  2222.     extends AbstractList<E>  
  2223.     implements RandomAccess, Serializable {  
  2224.   
  2225.         static final long serialVersionUID = 3093736618740652951L;  
  2226.   
  2227.         private final E element;  
  2228.   
  2229.         SingletonList(E obj)                {element = obj;}  
  2230.   
  2231.         public int size()                   {return 1;}  
  2232.   
  2233.         public boolean contains(Object obj) {return eq(obj, element);}  
  2234.   
  2235.         public E get(int index) {  
  2236.             if (index != 0)  
  2237.               throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");  
  2238.             return element;  
  2239.         }  
  2240.     }  
  2241.   
  2242.   
  2243.     public static <K,V> Map<K,V> singletonMap(K key, V value) {  
  2244.         return new SingletonMap<K,V>(key, value);  
  2245.     }  
  2246.   
  2247.     private static class SingletonMap<K,V> extends AbstractMap<K,V>  
  2248.       implements Serializable {  
  2249.         private static final long serialVersionUID = -6979724477215052911L;  
  2250.   
  2251.         private final K k;  
  2252.         private final V v;  
  2253.   
  2254.         SingletonMap(K key, V value) {  
  2255.             k = key;  
  2256.             v = value;  
  2257.         }  
  2258.   
  2259.         public int size()                          {return 1;}  
  2260.   
  2261.         public boolean isEmpty()                   {return false;}  
  2262.   
  2263.         public boolean containsKey(Object key)     {return eq(key, k);}  
  2264.   
  2265.         public boolean containsValue(Object value) {return eq(value, v);}  
  2266.   
  2267.         public V get(Object key)                   {return (eq(key, k) ? v : null);}  
  2268.   
  2269.         private transient Set<K> keySet = null;  
  2270.         private transient Set<Map.Entry<K,V>> entrySet = null;  
  2271.         private transient Collection<V> values = null;  
  2272.   
  2273.         public Set<K> keySet() {  
  2274.             if (keySet==null)  
  2275.                 keySet = singleton(k);  
  2276.             return keySet;  
  2277.         }  
  2278.   
  2279.         public Set<Map.Entry<K,V>> entrySet() {  
  2280.             if (entrySet==null)  
  2281.                 entrySet = Collections.<Map.Entry<K,V>>singleton(  
  2282.                         new SimpleImmutableEntry<K,V>(k, v));  
  2283.             return entrySet;  
  2284.         }  
  2285.   
  2286.         public Collection<V> values() {  
  2287.             if (values==null)  
  2288.             values = singleton(v);  
  2289.             return values;  
  2290.         }  
  2291.   
  2292.     }  
  2293.   
  2294.     /** 
  2295.      *  
  2296.      * 返回一个包含N个o元素的比可变的集合 
  2297.      * @param  n 添加的指定元素的个数 
  2298.      * @param  o 被重复添加的元素 
  2299.      */  
  2300.     public static <T> List<T> nCopies(int n, T o) {  
  2301.     if (n < 0)  
  2302.         throw new IllegalArgumentException("List length = " + n);  
  2303.         return new CopiesList<T>(n, o);  
  2304.     }  
  2305.   
  2306.     /** 
  2307.      * @serial include 
  2308.      */  
  2309.     private static class CopiesList<E>extends AbstractList<E>  
  2310.     implements RandomAccess, Serializable{  
  2311.         static final long serialVersionUID = 2739099268398711800L;  
  2312.   
  2313.         final int n;  
  2314.         final E element;  
  2315.   
  2316.         CopiesList(int n, E e) {  
  2317.         assert n >= 0;  
  2318.             this.n = n;  
  2319.             element = e;  
  2320.         }  
  2321.   
  2322.         public int size() {  
  2323.             return n;  
  2324.         }  
  2325.   
  2326.         public boolean contains(Object obj) {  
  2327.             return n != 0 && eq(obj, element);  
  2328.         }  
  2329.   
  2330.         public int indexOf(Object o) {  
  2331.             return contains(o) ? 0 : -1;  
  2332.         }  
  2333.   
  2334.         public int lastIndexOf(Object o) {  
  2335.             return contains(o) ? n - 1 : -1;  
  2336.         }  
  2337.   
  2338.         public E get(int index) {  
  2339.             if (index < 0 || index >= n)  
  2340.                 throw new IndexOutOfBoundsException("Index: "+index+  
  2341.                                                     ", Size: "+n);  
  2342.             return element;  
  2343.         }  
  2344.   
  2345.         public Object[] toArray() {  
  2346.             final Object[] a = new Object[n];  
  2347.             if (element != null)  
  2348.             Arrays.fill(a, 0, n, element);  
  2349.             return a;  
  2350.         }  
  2351.   
  2352.         public <T> T[] toArray(T[] a) {  
  2353.             final int n = this.n;  
  2354.             if (a.length < n) {  
  2355.             a = (T[])java.lang.reflect.Array  
  2356.                 .newInstance(a.getClass().getComponentType(), n);  
  2357.             if (element != null)  
  2358.                 Arrays.fill(a, 0, n, element);  
  2359.             } else {  
  2360.             Arrays.fill(a, 0, n, element);  
  2361.             if (a.length > n)  
  2362.                 a[n] = null;  
  2363.             }  
  2364.             return a;  
  2365.         }  
  2366.   
  2367.         public List<E> subList(int fromIndex, int toIndex) {  
  2368.             if (fromIndex < 0)  
  2369.             throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);  
  2370.             if (toIndex > n)  
  2371.             throw new IndexOutOfBoundsException("toIndex = " + toIndex);  
  2372.             if (fromIndex > toIndex)  
  2373.             throw new IllegalArgumentException("fromIndex(" + fromIndex +  
  2374.                                ") > toIndex(" + toIndex + ")");  
  2375.             return new CopiesList(toIndex - fromIndex, element);  
  2376.         }  
  2377.     }  
  2378.   
  2379.     /** 
  2380.      * 返回一个比较器,该比较器能使集合按降序排列 
  2381.      * 例如: 
  2382.      *      Arrays.sort(a, Collections.reverseOrder()); 
  2383.      *  能按字母表相反的顺序排列数组 
  2384.      *  
  2385.      */  
  2386.     public static <T> Comparator<T> reverseOrder() {  
  2387.         return (Comparator<T>) REVERSE_ORDER;  
  2388.     }  
  2389.   
  2390.     private static final Comparator REVERSE_ORDER = new ReverseComparator();  
  2391.   
  2392.     /** 
  2393.      * @serial include 
  2394.      */  
  2395.     private static class ReverseComparator<T>  
  2396.     implements Comparator<Comparable<Object>>, Serializable {  
  2397.   
  2398.     // use serialVersionUID from JDK 1.2.2 for interoperability  
  2399.     private static final long serialVersionUID = 7207038068494060240L;  
  2400.   
  2401.         public int compare(Comparable<Object> c1, Comparable<Object> c2) {  
  2402.             return c2.compareTo(c1);  
  2403.         }  
  2404.   
  2405.         private Object readResolve() { return reverseOrder(); }  
  2406.     }  
  2407.   
  2408.     /** 
  2409.      * 根据指定比较器的相反顺序排列集合 
  2410.      */  
  2411.     public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {  
  2412.         if (cmp == null)  
  2413.             return reverseOrder();  
  2414.         return new ReverseComparator2<T>(cmp);  
  2415.     }  
  2416.   
  2417.     /** 
  2418.      * @serial include 
  2419.      */  
  2420.     private static class ReverseComparator2<T> implements Comparator<T>,  
  2421.         Serializable{  
  2422.         private static final long serialVersionUID = 4374092139857L;  
  2423.   
  2424.    
  2425.         private Comparator<T> cmp;  
  2426.   
  2427.         ReverseComparator2(Comparator<T> cmp) {  
  2428.             assert cmp != null;  
  2429.             this.cmp = cmp;  
  2430.         }  
  2431.   
  2432.         public int compare(T t1, T t2) {  
  2433.             return cmp.compare(t2, t1);  
  2434.         }  
  2435.     }  
  2436.   
  2437.     /** 
  2438.      * 基于c之上返回一个枚举集 
  2439.      */  
  2440.     public static <T> Enumeration<T> enumeration(final Collection<T> c) {  
  2441.         return new Enumeration<T>() {  
  2442.             Iterator<T> i = c.iterator();  
  2443.       
  2444.             public boolean hasMoreElements() {  
  2445.                 return i.hasNext();  
  2446.             }  
  2447.       
  2448.             public T nextElement() {  
  2449.                 return i.next();  
  2450.             }  
  2451.          };  
  2452.     }  
  2453.   
  2454.     /** 
  2455.      * 根据枚举集中的元素返回一个ArrayList 
  2456.      */  
  2457.     public static <T> ArrayList<T> list(Enumeration<T> e) {  
  2458.         ArrayList<T> l = new ArrayList<T>();  
  2459.         while (e.hasMoreElements())  
  2460.             l.add(e.nextElement());  
  2461.         return l;  
  2462.     }  
  2463.   
  2464.     /** 
  2465.      * 判断两对象是否相等或同位空 
  2466.      */  
  2467.     private static boolean eq(Object o1, Object o2) {  
  2468.         return (o1==null ? o2==null : o1.equals(o2));  
  2469.     }  
  2470.   
  2471.     /** 
  2472.      * 返回c中与o相等的元素的个数 
  2473.      */  
  2474.     public static int frequency(Collection<?> c, Object o) {  
  2475.         int result = 0;  
  2476.         if (o == null) {  
  2477.             for (Object e : c)  
  2478.                 if (e == null)  
  2479.                     result++;  
  2480.         } else {  
  2481.             for (Object e : c)  
  2482.                 if (o.equals(e))  
  2483.                     result++;  
  2484.         }  
  2485.         return result;  
  2486.     }  
  2487.   
  2488.     /** 
  2489.      *  
  2490.      * 如果两指定集合没有共同的元素则返回true 
  2491.      */  
  2492.     public static boolean disjoint(Collection<?> c1, Collection<?> c2) {  
  2493.         /* 
  2494.          *  
  2495.          * 优先遍历的始终是size小的集合或非Set的集合 
  2496.          */  
  2497.         if ((c1 instanceof Set) && !(c2 instanceof Set) ||  
  2498.             (c1.size() > c2.size())) {  
  2499.             Collection<?> tmp = c1;  
  2500.             c1 = c2;  
  2501.             c2 = tmp;  
  2502.         }  
  2503.   
  2504.         for (Object e : c1)  
  2505.             if (c2.contains(e))  
  2506.                 return false;  
  2507.         return true;  
  2508.     }  
  2509.   
  2510.     /** 
  2511.      * 把所有指定元素添加到集合c中, 
  2512.      * 有一个元素添加成功就返回true 
  2513.      */  
  2514.     public static <T> boolean addAll(Collection<? super T> c, T... elements) {  
  2515.         boolean result = false;  
  2516.         for (T element : elements)  
  2517.             result |= c.add(element);  
  2518.         return result;  
  2519.     }  
  2520.   
  2521.     /** 
  2522.      * 根据指定的map返回一个set 
  2523.      * set存储的是map的键值 
  2524.      */  
  2525.     public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {  
  2526.         return new SetFromMap<E>(map);  
  2527.     }  
  2528.   
  2529.     private static class SetFromMap<E> extends AbstractSet<E>  
  2530.         implements Set<E>, Serializable  
  2531.     {  
  2532.         private final Map<E, Boolean> m;  // The backing map  
  2533.         private transient Set<E> s;       // Its keySet  
  2534.   
  2535.         SetFromMap(Map<E, Boolean> map) {  
  2536.             if (!map.isEmpty())  
  2537.                 throw new IllegalArgumentException("Map is non-empty");  
  2538.             m = map;  
  2539.             s = map.keySet();  
  2540.         }  
  2541.   
  2542.         public void clear()               {        m.clear(); }  
  2543.         public int size()                 { return m.size(); }  
  2544.         public boolean isEmpty()          { return m.isEmpty(); }  
  2545.         public boolean contains(Object o) { return m.containsKey(o); }  
  2546.         public boolean remove(Object o)   { return m.remove(o) != null; }  
  2547.         public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }  
  2548.         public Iterator<E> iterator()     { return s.iterator(); }  
  2549.         public Object[] toArray()         { return s.toArray(); }  
  2550.         public <T> T[] toArray(T[] a)     { return s.toArray(a); }  
  2551.         public String toString()          { return s.toString(); }  
  2552.         public int hashCode()             { return s.hashCode(); }  
  2553.         public boolean equals(Object o)   { return o == this || s.equals(o); }  
  2554.         public boolean containsAll(Collection<?> c) {return s.containsAll(c);}  
  2555.         public boolean removeAll(Collection<?> c)   {return s.removeAll(c);}  
  2556.         public boolean retainAll(Collection<?> c)   {return s.retainAll(c);}  
  2557.     // addAll is the only inherited implementation  
  2558.   
  2559.         private static final long serialVersionUID = 2454657854757543876L;  
  2560.   
  2561.         private void readObject(java.io.ObjectInputStream stream)  
  2562.             throws IOException, ClassNotFoundException  
  2563.         {  
  2564.             stream.defaultReadObject();  
  2565.             s = m.keySet();  
  2566.         }  
  2567.     }  
  2568.   
  2569.     /** 
  2570.      *  
  2571.      * 把指定Deque包装成一个后进先出的队列 
  2572.      * add方法对应push,remove方法对应pop等。 
  2573.      *  
  2574.      */  
  2575.     public static <T> Queue<T> asLifoQueue(Deque<T> deque) {  
  2576.         return new AsLIFOQueue<T>(deque);  
  2577.     }  
  2578.   
  2579.     static class AsLIFOQueue<E> extends AbstractQueue<E>  
  2580.         implements Queue<E>, Serializable {  
  2581.     private static final long serialVersionUID = 1802017725587941708L;  
  2582.         private final Deque<E> q;  
  2583.         AsLIFOQueue(Deque<E> q)           { this.q = q; }  
  2584.         public boolean add(E e)           { q.addFirst(e); return true; }  
  2585.         public boolean offer(E e)         { return q.offerFirst(e); }  
  2586.         public E poll()                   { return q.pollFirst(); }  
  2587.         public E remove()                 { return q.removeFirst(); }  
  2588.         public E peek()                   { return q.peekFirst(); }  
  2589.         public E element()                { return q.getFirst(); }  
  2590.         public void clear()               {        q.clear(); }  
  2591.         public int size()                 { return q.size(); }  
  2592.         public boolean isEmpty()          { return q.isEmpty(); }  
  2593.         public boolean contains(Object o) { return q.contains(o); }  
  2594.         public boolean remove(Object o)   { return q.remove(o); }  
  2595.         public Iterator<E> iterator()     { return q.iterator(); }  
  2596.         public Object[] toArray()         { return q.toArray(); }  
  2597.         public <T> T[] toArray(T[] a)     { return q.toArray(a); }  
  2598.         public String toString()          { return q.toString(); }  
  2599.     public boolean containsAll(Collection<?> c) {return q.containsAll(c);}  
  2600.     public boolean removeAll(Collection<?> c)   {return q.removeAll(c);}  
  2601.     public boolean retainAll(Collection<?> c)   {return q.retainAll(c);}  
  2602.     // We use inherited addAll; forwarding addAll would be wrong  
  2603.     }  
  2604. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值