集合框架源码分析二(抽象类篇)

来源:互联网 发布:网络销售属于什么行业 编辑:程序博客网 时间:2024/06/05 14:47
一。AbstractCollection
Java代码  收藏代码
  1. public abstract class AbstractCollection<E> implements Collection<E> {  
  2.     /** 
  3.      * 唯一构造方法 
  4.      */  
  5.     protected AbstractCollection() {  
  6.     }  
  7.   
  8.     // Query Operations  
  9.   
  10.     /** 
  11.      * 
  12.      * 返回集合中元素的迭代器 
  13.      */  
  14.     public abstract Iterator<E> iterator();  
  15.   
  16.     public abstract int size();  
  17.   
  18.     public boolean isEmpty() {  
  19.     return size() == 0;   //size=0则此方法返回true  
  20.     }  
  21.   
  22.     public boolean contains(Object o) {  
  23.     Iterator<E> e = iterator();   //获取此集合的迭代器  
  24.     if (o==null) {                 
  25.         while (e.hasNext())        
  26.         if (e.next()==null)   //如果此集合允许null元素,找到则返回true  
  27.             return true;  
  28.     } else {  
  29.         while (e.hasNext())  
  30.         if (o.equals(e.next()))  
  31.             return true;  
  32.     }  
  33.     return false;  
  34.     }  
  35.   
  36.     /** 
  37.      * 此方法是同步的,即使在遍历集合的过程中发现集合已经改变,任然可以返回 
  38.      * 正确的结果 
  39.      * 
  40.      * 此方法等同于: 
  41.      * 
  42.      * List<E> list = new ArrayList<E>(size()); 
  43.      * for (E e : this) 
  44.      *     list.add(e); 
  45.      * return list.toArray(); 
  46.      */  
  47.     public Object[] toArray() {  
  48.     Object[] r = new Object[size()]; //新建一个对象数组,长度为集合的长度  
  49.         Iterator<E> it = iterator();  
  50.     for (int i = 0; i < r.length; i++) {    //遍历赋值  
  51.         if (! it.hasNext()) // 遍历过程中,集合中有元素被移除,长度减少  
  52.         return Arrays.copyOf(r, i);  //则仅返回长度为i的数组,i=当前集合长度  
  53.         r[i] = it.next();  
  54.     }  
  55.         //如果遍历完后发现集合还有更多的元素,即在遍历时有元素被添加进集合,调用  
  56.         //finishToArray方法添加剩余的元素  
  57.     return it.hasNext() ? finishToArray(r, it) : r;  
  58.     }  
  59.   
  60.      
  61.     public <T> T[] toArray(T[] a) {  
  62.         int size = size();      //当前集合长度  
  63.         T[] r = a.length >= size ? a :  //如果a的长度大于等于size,把a赋给r,否则新建一个元素类型为a元素类型,size长度的数组  
  64.                   (T[])java.lang.reflect.Array  
  65.                   .newInstance(a.getClass().getComponentType(), size);  
  66.         Iterator<E> it = iterator();  
  67.   
  68.     for (int i = 0; i < r.length; i++) {  
  69.         if (! it.hasNext()) { 遍历过程中,集合中有元素被移除,长度减少.或遍历集合结束  
  70.         if (a != r)   //表明是新建的数组  
  71.             return Arrays.copyOf(r, i);  
  72.         r[i] = null// 表明是a,则多加一个null结束符  
  73.         return r;  
  74.         }  
  75.         r[i] = (T)it.next();  
  76.     }  
  77.     return it.hasNext() ? finishToArray(r, it) : r;  
  78.     }  
  79.   
  80.     /** 
  81.      * 当it还有更多的元素,重新分配数组。并把剩余元素添加进数组 
  82.      */  
  83.     private static <T> T[] finishToArray(T[] r, Iterator<?> it) {  
  84.         int i = r.length;         //原来数组长度存入i中  
  85.         while (it.hasNext()) {  
  86.             int cap = r.length;     
  87.             if (i == cap) {   //表明未重新分配数组长度  
  88.                 int newCap = ((cap / 2) + 1) * 3;   //新数组长度的计算公式,大约扩充1.5倍  
  89.                 if (newCap <= cap) { // 如果分配后发生了整型溢出  
  90.                     if (cap == Integer.MAX_VALUE)  
  91.                         throw new OutOfMemoryError("Required array size too large");  
  92.                     newCap = Integer.MAX_VALUE;      
  93.                 }  
  94.                 r = Arrays.copyOf(r, newCap); //新建一个长度为newCap的数组,并把r中数据存入  
  95.             }  
  96.             r[i++] = (T) it.next();   //添加集合剩余元素到新数组  
  97.         }  
  98.         // 修剪多余的长度  
  99.         return (i == r.length) ? r : Arrays.copyOf(r, i);  
  100.     }  
  101.   
  102.     // Modification Operations  
  103.   
  104.     /** 
  105.      * 调用此方法总是抛出一个异常,需要子类去重写此方法 
  106.      */  
  107.     public boolean add(E e) {  
  108.     throw new UnsupportedOperationException();  
  109.     }  
  110.   
  111.     /** 
  112.      * 此方法会首先在集合中查找指定元素o,如果找到就移除它 
  113.      * 移除的是第一个找到的匹配的值 
  114.      */  
  115.     public boolean remove(Object o) {  
  116.     Iterator<E> e = iterator();  
  117.     if (o==null) {       //集合支持null元素  
  118.         while (e.hasNext()) {  
  119.         if (e.next()==null) {  
  120.             e.remove();       
  121.             return true;  
  122.         }  
  123.         }  
  124.     } else {  
  125.         while (e.hasNext()) {  
  126.         if (o.equals(e.next())) {  
  127.             e.remove();  
  128.             return true;  
  129.         }  
  130.         }  
  131.     }  
  132.     return false;  
  133.     }  
  134.   
  135.   
  136.     // Bulk Operations  
  137.   
  138.      
  139.     public boolean containsAll(Collection<?> c) {  
  140.     Iterator<?> e = c.iterator();  
  141.     while (e.hasNext())  
  142.         if (!contains(e.next()))  //如果c中有一个元素不在本集合中则返回false  
  143.         return false;  
  144.     return true;  
  145.     }  
  146.   
  147.     /** 
  148.      * 此方法将抛出一个UnsupportedOperationException,除非子类重写了add方法 
  149.      */  
  150.     public boolean addAll(Collection<? extends E> c) {  
  151.     boolean modified = false;  
  152.     Iterator<? extends E> e = c.iterator();  
  153.     while (e.hasNext()) {  
  154.         if (add(e.next()))   //如果有一个元素添加失败就返回false  
  155.             modified = true;  
  156.     }  
  157.     return modified;  
  158.     }  
  159.   
  160.   
  161.     public boolean removeAll(Collection<?> c) {  
  162.     boolean modified = false;  
  163.     Iterator<?> e = iterator();  
  164.     while (e.hasNext()) {  
  165.         if (c.contains(e.next())) { //如果c中元素也保含在本集合中则移除它  
  166.             e.remove();  
  167.             modified = true;  
  168.         }  
  169.     }  
  170.     return modified;  
  171.     }  
  172.   
  173.    public boolean retainAll(Collection<?> c) {  
  174.         boolean modified = false;  
  175.         Iterator<E> e = iterator();  
  176.         while (e.hasNext()) {  
  177.             if (!c.contains(e.next())) {  //遍历集合元素,如果元素不包含在c中,则移除此元素  
  178.                 e.remove();               //取的是交集  
  179.                 modified = true;  
  180.             }  
  181.         }  
  182.         return modified;  
  183.     }  
  184.   
  185.   
  186.     public void clear() {  
  187.     Iterator<E> e = iterator();  
  188.     while (e.hasNext()) {    //依次调用next和remove方法  
  189.         e.next();  
  190.         e.remove();  
  191.     }  
  192.     }  
  193.   
  194.   
  195.     //  String conversion  
  196.   
  197.    /** 
  198.      * 重写toString方法,返回格式:[e.toString, e2.toString, ...] 
  199.      * */  
  200.     public String toString() {  
  201.         Iterator<E> i = iterator();  
  202.         if (!i.hasNext())   //如果集合为空返回[]  
  203.             return "[]";  
  204.         StringBuilder sb = new StringBuilder();  
  205.         sb.append('[');  
  206.         for (;;) {  
  207.             E e = i.next();  
  208.             sb.append(e == this ? "(this Collection)" : e);  
  209.             if (!i.hasNext())  
  210.                 return sb.append(']').toString();  
  211.             sb.append(", ");  
  212.         }  
  213.     }  
  214.   
  215. }  



二。AbstractList<E>
Java代码  收藏代码
  1. public abstract class AbstractList<E> extends AbstractCollection<E> implements  
  2.         List<E> {  
  3.     /** 
  4.      * 唯一构造方法 
  5.      */  
  6.     protected AbstractList() {  
  7.     }  
  8.   
  9.     /** 
  10.      * 添加指定元素到List的最后 
  11.      * 此方法将抛出一个UnsupportedOperationException除非List的子类重写了add(int,E)方法 
  12.      *  
  13.      */  
  14.     public boolean add(E e) {  
  15.         add(size(), e); //如果List子类没有重写此方法会抛出一个异常  
  16.         return true;  
  17.     }  
  18.   
  19.     abstract public E get(int index);  
  20.   
  21.     /** 
  22.      * 总是抛出一个UnsupportedOperationException,除非子类重写了此方法 
  23.      */  
  24.     public E set(int index, E element) {  
  25.         throw new UnsupportedOperationException();  
  26.     }  
  27.   
  28.     /** 
  29.      * 总是抛出一个UnsupportedOperationException,除非子类重写了此方法 
  30.      */  
  31.     public void add(int index, E element) {  
  32.         throw new UnsupportedOperationException();  
  33.     }  
  34.   
  35.     /** 
  36.      * 总是抛出一个UnsupportedOperationException,除非子类重写了此方法 
  37.      */  
  38.     public E remove(int index) {  
  39.         throw new UnsupportedOperationException();  
  40.     }  
  41.   
  42.     // Search Operations  
  43.       
  44.     public int indexOf(Object o) {  
  45.         ListIterator<E> e = listIterator();   //使用listIterator  
  46.         if (o == null) {  
  47.             while (e.hasNext())  
  48.                 if (e.next() == null)  
  49.                     return e.previousIndex();  
  50.         } else {  
  51.             while (e.hasNext())  
  52.                 if (o.equals(e.next()))  
  53.                     return e.previousIndex();  
  54.         }  
  55.         return -1;   //返回-1表示遍历到了集合最后都没有找到指定元素o  
  56.     }  
  57.   
  58.   
  59.     public int lastIndexOf(Object o) {  
  60.         ListIterator<E> e = listIterator(size());  
  61.         if (o == null) {  
  62.             while (e.hasPrevious())       //从后面开始遍历  
  63.                 if (e.previous() == null)  
  64.                     return e.nextIndex();  
  65.         } else {  
  66.             while (e.hasPrevious())  
  67.                 if (o.equals(e.previous()))  
  68.                     return e.nextIndex();  
  69.         }  
  70.         return -1;  
  71.     }  
  72.   
  73.     // Bulk Operations  
  74.   
  75.     public void clear() {  
  76.         removeRange(0, size());   //清空指定范围的元素  
  77.     }  
  78.   
  79.       
  80.     public boolean addAll(int index, Collection<? extends E> c) {  
  81.         boolean modified = false;  
  82.         Iterator<? extends E> e = c.iterator();  
  83.         while (e.hasNext()) {  
  84.             add(index++, e.next());  //把c中元素添加到指定位置,此add方法由子类实现  
  85.             modified = true;  
  86.         }  
  87.         return modified;  
  88.     }  
  89.   
  90.     // Iterators  
  91.   
  92.   
  93.     public Iterator<E> iterator() {  
  94.         return new Itr();      //返回实现了Iterator接口的类  
  95.     }  
  96.   
  97.       
  98.     public ListIterator<E> listIterator() {  
  99.         return listIterator(0);   //返回一个listIterator,遍历起点为0  
  100.     }  
  101.   
  102.       
  103.     public ListIterator<E> listIterator(final int index) {  
  104.         if (index < 0 || index > size())       //index超出集合范围则抛出越界异常  
  105.             throw new IndexOutOfBoundsException("Index: " + index);  
  106.   
  107.         return new ListItr(index);  
  108.     }  
  109.       
  110.     /** 
  111.      * 实现了Iterator接口中的所有方法 
  112.      * */  
  113.     private class Itr implements Iterator<E> {  
  114.         /** 
  115.          * 游标,随后调用next时返回的元素的索引 
  116.          */  
  117.         int cursor = 0;  
  118.   
  119.         /** 
  120.          * 最近一次调用next或previous时返回的元素的索引 
  121.          */  
  122.         int lastRet = -1;  
  123.   
  124.         /** 
  125.          * 如果他们不相等说明迭代器检查到了并发操作 
  126.          */  
  127.         int expectedModCount = modCount;  
  128.   
  129.         public boolean hasNext() {  
  130.             return cursor != size();    //根据cursor大小来判断集合是否还有更多的元素  
  131.         }  
  132.   
  133.         public E next() {  
  134.             checkForComodification();   //检测是否是并发操作  
  135.             try {  
  136.                 E next = get(cursor);  //返回索引为cursor的元素  
  137.                 lastRet = cursor++;    //调用next时cursor自增了  
  138.                 return next;  
  139.             } catch (IndexOutOfBoundsException e) {  //如果索引超出集合边界则抛出IndexOutOfBoundsException  
  140.                 checkForComodification();     //如果IndexOutOfBoundsException是由并发操作引起的则抛出NoSuchElementException  
  141.                 throw new NoSuchElementException();  
  142.             }  
  143.         }  
  144.   
  145.         public void remove() {  
  146.             if (lastRet == -1)   //这是为了判断是否调用了next方法  
  147.                 throw new IllegalStateException();  //否则抛出IllegalStateException  
  148.             checkForComodification();   //同样要检查是否是并发操作  
  149.   
  150.             try {  
  151.                 AbstractList.this.remove(lastRet);  //迭代器的remove方法即是List的remove方法  
  152.                 if (lastRet < cursor)  //在不断调用next方法时lastRet必然小于cursor,删除lastRet位置元素后cursor--,lastRet复位  
  153.                     cursor--;  
  154.                 lastRet = -1;  
  155.                 expectedModCount = modCount;     
  156.             } catch (IndexOutOfBoundsException e) {  
  157.                 throw new ConcurrentModificationException();  
  158.             }  
  159.         }  
  160.   
  161.         final void checkForComodification() {  
  162.             if (modCount != expectedModCount)  
  163.                 throw new ConcurrentModificationException();  
  164.         }  
  165.     }  
  166.   
  167.     private class ListItr extends Itr implements ListIterator<E> {  
  168.         ListItr(int index) {    //构造函数,传进cursor  
  169.             cursor = index;  
  170.         }  
  171.   
  172.         public boolean hasPrevious() {    //当前cursor不为0则有前驱  
  173.             return cursor != 0;  
  174.         }  
  175.   
  176.         public E previous() {  //前驱元素的索引为cursor-1  
  177.             checkForComodification();  
  178.             try {  
  179.                 int i = cursor - 1;  
  180.                 E previous = get(i);  
  181.                 lastRet = cursor = i;   //lastRet为返回元素的索引  
  182.                 return previous;  
  183.             } catch (IndexOutOfBoundsException e) {  
  184.                 checkForComodification();  
  185.                 throw new NoSuchElementException();  
  186.             }  
  187.         }  
  188.   
  189.         public int nextIndex() {  //下一次调用next返回的元素的索引,即为cursor  
  190.             return cursor;  
  191.         }  
  192.   
  193.         public int previousIndex() { //下一次调用previous方法返回的元素的索引  
  194.             return cursor - 1;  
  195.         }  
  196.   
  197.         public void set(E e) {  
  198.             if (lastRet == -1)  //表明没有调用next或previous方法  
  199.                 throw new IllegalStateException();  
  200.             checkForComodification();  
  201.   
  202.             try {  
  203.                 AbstractList.this.set(lastRet, e);    //lastRet为修改元素的索引  
  204.                 expectedModCount = modCount;  
  205.             } catch (IndexOutOfBoundsException ex) {  
  206.                 throw new ConcurrentModificationException();  
  207.             }  
  208.         }  
  209.   
  210.         public void add(E e) {  
  211.             checkForComodification();  
  212.   
  213.             try {  
  214.                 AbstractList.this.add(cursor++, e);   //将元素e插入到调用next方法返回的元素之后,或者调用previous方法返回的元素之前  
  215.                 lastRet = -1;       //重置lastRet  
  216.                 expectedModCount = modCount;  
  217.             } catch (IndexOutOfBoundsException ex) {  
  218.                 throw new ConcurrentModificationException();  
  219.             }  
  220.         }  
  221.     }  
  222.   
  223.     /** 
  224.      * new RandomAccessSubList<E>与new SubList<E>的区别是返回的子集合是否实现了RandomAccess 
  225.      * 返回的是一个新的subList类,该类继承自AbstractList,实现了AbstractList的所有行为 
  226.      */  
  227.     public List<E> subList(int fromIndex, int toIndex) {  
  228.         return (this instanceof RandomAccess ? new RandomAccessSubList<E>(this,  
  229.                 fromIndex, toIndex) : new SubList<E>(this, fromIndex, toIndex));  
  230.     }  
  231.   
  232.     // Comparison and hashing  
  233.   
  234.       
  235.     public boolean equals(Object o) {  
  236.         if (o == this)           //o为本集合返回true  
  237.             return true;   
  238.         if (!(o instanceof List))   //如果o没有实现List接口直接返回false  
  239.             return false;  
  240.   
  241.         ListIterator<E> e1 = listIterator();  
  242.         ListIterator e2 = ((List) o).listIterator();  
  243.         while (e1.hasNext() && e2.hasNext()) {   //按位序依次遍历比较  
  244.             E o1 = e1.next();  
  245.             Object o2 = e2.next();  
  246.             if (!(o1 == null ? o2 == null : o1.equals(o2))) //比较o1与o2,不相等则返回flase  
  247.                 return false;  
  248.         }  
  249.         //检查长度是否相等  
  250.         return !(e1.hasNext() || e2.hasNext());     
  251.     }  
  252.   
  253.       
  254.     public int hashCode() {  
  255.         int hashCode = 1;  
  256.         Iterator<E> i = iterator();  
  257.         while (i.hasNext()) {  
  258.             E obj = i.next();  
  259.             //List hashCode的 计算公式  
  260.             hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());  
  261.         }  
  262.         return hashCode;  
  263.     }  
  264.   
  265.     /** 
  266.      *  
  267.      * 移除指定范围的元素,左移随后的元素,并减少它们的索引 
  268.      * 如果toIndex=fromIndex,此操作无影响 
  269.      *  
  270.      */  
  271.     protected void removeRange(int fromIndex, int toIndex) {  
  272.         ListIterator<E> it = listIterator(fromIndex); //是迭代器定位到fromIndex位置  
  273.         for (int i = 0, n = toIndex - fromIndex; i < n; i++) {   //移除toIndex - fromIndex个数元素  
  274.             it.next();  
  275.             it.remove();  
  276.         }  
  277.     }  
  278.   
  279.     /** 
  280.      * 此变量是用来检查iterator中的同步,在所有的对List的结构性操作中 
  281.      * 此modCount的值都会加1,比如add()、remove()、addAll()、clear()等 
  282.      */  
  283.     protected transient int modCount = 0;  
  284. }  
  285.   
  286.   
  287. /** 
  288.  * 主要功能用于获取集合完整结构的子范围, 
  289.  * 该类继承自AbstractList,拥有AbstractList中的所有操作 
  290.  * 对子范围进行操作会影响AbstractList,因为AbstractList被作为参数传进 
  291.  * 了SubList<E>,对SubList的操作其实是对AbstractList的操作 
  292.  * */  
  293. class SubList<E> extends AbstractList<E> {  
  294.     private AbstractList<E> l;  
  295.     private int offset;  
  296.     private int size;  
  297.     private int expectedModCount;  
  298.   
  299.     SubList(AbstractList<E> list, int fromIndex, int toIndex) {   //初始化  
  300.         if (fromIndex < 0)  
  301.             throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);  
  302.         if (toIndex > list.size())  
  303.             throw new IndexOutOfBoundsException("toIndex = " + toIndex);  
  304.         if (fromIndex > toIndex)  
  305.             throw new IllegalArgumentException("fromIndex(" + fromIndex  
  306.                     + ") > toIndex(" + toIndex + ")");  
  307.         l = list;  
  308.         offset = fromIndex;   //起始索引  
  309.         size = toIndex - fromIndex;  //子集长度  
  310.         expectedModCount = l.modCount;  //用于检查是否发生了并发操作  
  311.     }  
  312.   
  313.     public E set(int index, E element) {  
  314.         rangeCheck(index);      //检查索引是否合法,即是否在0到size之间,不包含size  
  315.         checkForComodification();     
  316.         return l.set(index + offset, element);  //对子集的操作其实是对原来集合的操作  
  317.     }  
  318.   
  319.     public E get(int index) {  
  320.         rangeCheck(index);  
  321.         checkForComodification();  
  322.         return l.get(index + offset);  
  323.     }  
  324.   
  325.     public int size() {  
  326.         checkForComodification();  
  327.         return size;  
  328.     }  
  329.   
  330.     public void add(int index, E element) {  
  331.         if (index < 0 || index > size)   //可以等于size,表示添加 到最后  
  332.             throw new IndexOutOfBoundsException();  
  333.         checkForComodification();  
  334.         l.add(index + offset, element);  
  335.         expectedModCount = l.modCount;  
  336.         size++;  
  337.         modCount++;         //调用add方法集合结构发生改变时modCount++  
  338.     }  
  339.   
  340.     public E remove(int index) {  
  341.         rangeCheck(index);  
  342.         checkForComodification();  
  343.         E result = l.remove(index + offset);  
  344.         expectedModCount = l.modCount;  
  345.         size--;  
  346.         modCount++;     // 调用remove方法集合结构发生改变时modCount++  
  347.         return result;  
  348.     }  
  349.   
  350.     protected void removeRange(int fromIndex, int toIndex) {  
  351.         checkForComodification();  
  352.         l.removeRange(fromIndex + offset, toIndex + offset);  
  353.         expectedModCount = l.modCount;  
  354.         size -= (toIndex - fromIndex);  //size相应减少  
  355.         modCount++;         // 调用removeRange方法集合结构发生改变时modCount++  
  356.     }  
  357.   
  358.     public boolean addAll(Collection<? extends E> c) {  
  359.         return addAll(size, c);     //在最后位置添加元素  
  360.     }  
  361.   
  362.     public boolean addAll(int index, Collection<? extends E> c) {  //在指定位置添加元素  
  363.         if (index < 0 || index > size)  
  364.             throw new IndexOutOfBoundsException("Index: " + index + ", Size: "  
  365.                     + size);  
  366.         int cSize = c.size();  
  367.         if (cSize == 0)  
  368.             return false;  
  369.   
  370.         checkForComodification();  
  371.         l.addAll(offset + index, c);  
  372.         expectedModCount = l.modCount;  
  373.         size += cSize;  //size相应增加  
  374.         modCount++;     // 调用addAll方法使集合结构发生改变时modCount++  
  375.         return true;  
  376.     }  
  377.   
  378.     public Iterator<E> iterator() {  
  379.         return listIterator();  
  380.     }  
  381.   
  382.     public ListIterator<E> listIterator(final int index) {  
  383.         checkForComodification();  
  384.         if (index < 0 || index > size)  
  385.             throw new IndexOutOfBoundsException("Index: " + index + ", Size: "  
  386.                     + size);  
  387.   
  388.         /** 
  389.          * 使用的还是父集合的listIterator方法 
  390.          * 操作的实际是父元素 
  391.          * */  
  392.         return new ListIterator<E>() {  
  393.             private ListIterator<E> i = l.listIterator(index + offset); //定位迭代器  
  394.   
  395.             public boolean hasNext() {  
  396.                 return nextIndex() < size;  
  397.             }  
  398.   
  399.             public E next() {  
  400.                 if (hasNext())  
  401.                     return i.next();  
  402.                 else  
  403.                     throw new NoSuchElementException();  
  404.             }  
  405.   
  406.             public boolean hasPrevious() {  
  407.                 return previousIndex() >= 0;  
  408.             }  
  409.   
  410.             public E previous() {  
  411.                 if (hasPrevious())  
  412.                     return i.previous();  
  413.                 else  
  414.                     throw new NoSuchElementException();  
  415.             }  
  416.   
  417.             public int nextIndex() {      
  418.                 return i.nextIndex() - offset;  
  419.             }  
  420.   
  421.             public int previousIndex() {  
  422.                 return i.previousIndex() - offset;  
  423.             }  
  424.   
  425.             public void remove() {  
  426.                 i.remove();  
  427.                 expectedModCount = l.modCount;  
  428.                 size--;  
  429.                 modCount++;  // 调用迭代器的remove方法使集合结构发生改变时modCount++  
  430.             }  
  431.   
  432.             public void set(E e) {  
  433.                 i.set(e);  
  434.             }  
  435.   
  436.             public void add(E e) {  
  437.                 i.add(e);  
  438.                 expectedModCount = l.modCount;  
  439.                 size++;  
  440.                 modCount++; // 调用迭代器的add方法使集合结构发生改变时modCount++  
  441.             }  
  442.         };  
  443.     }  
  444.   
  445.     public List<E> subList(int fromIndex, int toIndex) {  //subList的subList方法  
  446.         return new SubList<E>(this, fromIndex, toIndex);  
  447.     }  
  448.   
  449.     private void rangeCheck(int index) {  
  450.         if (index < 0 || index >= size)  
  451.             throw new IndexOutOfBoundsException("Index: " + index + ",Size: "  
  452.                     + size);  
  453.     }  
  454.   
  455.     private void checkForComodification() {  
  456.         if (l.modCount != expectedModCount)  
  457.             throw new ConcurrentModificationException();  
  458.     }  
  459. }  
  460.   
  461. /** 
  462.  * 支持随机访问的RandomAccessSubList类需要实现RandomAccess接口和重写subList方法 
  463.  * 其他同SubList<E>类 
  464.  * */  
  465. class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {  
  466.     RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {  
  467.         super(list, fromIndex, toIndex);      
  468.     }  
  469.   
  470.     public List<E> subList(int fromIndex, int toIndex) {  //需重写其subList方法,也使其实现RandomAccess接口  
  471.         return new RandomAccessSubList<E>(this, fromIndex, toIndex);  
  472.     }  
  473. }  



三。AbstractSet
Java代码  收藏代码
  1. public abstract class AbstractSet<E> extends AbstractCollection<E> implements  
  2.         Set<E> {  
  3.     /** 
  4.      * 唯一构造器 
  5.      */  
  6.     protected AbstractSet() {  
  7.     }  
  8.   
  9.     // Comparison and hashing  
  10.   
  11.     /** 
  12.      * 
  13.      */  
  14.     public boolean equals(Object o) {  
  15.         if (o == this)   //o就是本集合返回true  
  16.             return true;  
  17.   
  18.         if (!(o instanceof Set))  //o不是一个Set,即没有实现Set接口,肯定返回false  
  19.             return false;  
  20.         Collection c = (Collection) o;  //这句话可能抛出ClassCastException  
  21.         if (c.size() != size())     //长度不等则返回false  
  22.             return false;  
  23.         try {  
  24.             return containsAll(c);  //如果c中元素都包含在本集合中则返回true  
  25.         } catch (ClassCastException unused) {  
  26.             return false;  
  27.         } catch (NullPointerException unused) {   //o为空抛出NullPointerException  
  28.             return false;  
  29.         }  
  30.     }  
  31.   
  32.     /** 
  33.      * Set的hashCode值为所有元素的hashCode值之和 
  34.      */  
  35.     public int hashCode() {  
  36.         int h = 0;  
  37.         Iterator<E> i = iterator();  
  38.         while (i.hasNext()) {  
  39.             E obj = i.next();  
  40.             if (obj != null)  
  41.                 h += obj.hashCode();  
  42.         }  
  43.         return h;  
  44.     }  
  45.   
  46.     /** 
  47.      *  
  48.      * 移除Set中所有包含在c中的元素 
  49.      * 此方法的实现原则是:如果Set含有更少的元素,就遍历set,依次检查每个迭代返回的 
  50.      * 元素,看它是否包含在指定集合c中,如果包含就调用迭代器的remove方法移除它。 
  51.      * 如果指定集合c含有更少的元素,就遍历c,调用Set的remove方法移除通过迭代器返回的元素 
  52.      */  
  53.     public boolean removeAll(Collection<?> c) {  
  54.         boolean modified = false;  
  55.   
  56.         if (size() > c.size()) {  
  57.             for (Iterator<?> i = c.iterator(); i.hasNext();)  
  58.                 modified |= remove(i.next());   // |=表明只要一次remove方法返回true,modified就位true  
  59.         } else {  
  60.             for (Iterator<?> i = iterator(); i.hasNext();) {  
  61.                 if (c.contains(i.next())) {  
  62.                     i.remove();  
  63.                     modified = true;  
  64.                 }  
  65.             }  
  66.         }  
  67.         return modified;  
  68.     }  
  69.   
  70. }  



四。AbstractQueue
Java代码  收藏代码
  1. public abstract class AbstractQueue<E> extends AbstractCollection<E> implements  
  2.         Queue<E> {  
  3.   
  4.     /** 
  5.      * Constructor for use by subclasses. 
  6.      */  
  7.     protected AbstractQueue() {  
  8.     }  
  9.   
  10.     /** 
  11.      * 此内部实现为offer方法,由其子类实现。 
  12.      * 如果queue中有足够的容量则向其中插入e,否则抛出IllegalStateException 
  13.      */  
  14.     public boolean add(E e) {  
  15.         if (offer(e))  
  16.             return true;  
  17.         else  
  18.             throw new IllegalStateException("Queue full");  
  19.     }  
  20.   
  21.     /** 
  22.      * 此内部实现为poll()方法,由其子类实现。 
  23.      * poll方法返回不为空则表示移除头结点成功 
  24.      * 否则抛出NoSuchElementException 
  25.      */  
  26.     public E remove() {  
  27.         E x = poll();  
  28.         if (x != null)  //x为空则表示queue为空  
  29.             return x;  
  30.         else  
  31.             throw new NoSuchElementException();  
  32.     }  
  33.   
  34.     /** 
  35.      * 返回其头结点,但并不移除它 
  36.      * 此方法内部由peek()实现,peek由其子类实现 
  37.      * peek方法返回不为空则表示返回头结点成功, 
  38.      * 否则抛出NoSuchElementException 
  39.      */  
  40.     public E element() {  
  41.         E x = peek();  
  42.         if (x != null//x为空则表示queue为空  
  43.             return x;  
  44.         else  
  45.             throw new NoSuchElementException();  
  46.     }  
  47.   
  48.     /** 
  49.      * 移除queue中所有元素 
  50.      * 依次调用poll方法移除头结点 
  51.      */  
  52.     public void clear() {  
  53.         while (poll() != null)  
  54.             ;  
  55.     }  
  56.   
  57.     /** 
  58.      * 重写addAll方法 
  59.      */  
  60.     public boolean addAll(Collection<? extends E> c) {  
  61.         if (c == null)  //queue不支持null元素  
  62.             throw new NullPointerException();  
  63.         if (c == this)  
  64.             throw new IllegalArgumentException();  
  65.         boolean modified = false;  
  66.         Iterator<? extends E> e = c.iterator();  
  67.         while (e.hasNext()) {  
  68.             if (add(e.next()))  //调用的是AbstractQueue的add方法,调用此方法可能抛出异常  
  69.                 modified = true;  
  70.         }  
  71.         return modified;  
  72.     }  
  73.   
  74. }  



五。AbstractSequentialList
Java代码  收藏代码
  1. /** 
  2.  * 实现部分基础方法,使子类LinkedList不必再去实现 
  3.  * 实现了get,set,add,remove,addAll,iterator,listIterator方法 
  4.  * */  
  5. public abstract class AbstractSequentialList<E> extends AbstractList<E> {  
  6.     /** 
  7.      * Sole constructor.  (For invocation by subclass constructors, typically 
  8.      * implicit.) 
  9.      */  
  10.     protected AbstractSequentialList() {  
  11.     }  
  12.   
  13.     /** 
  14.      * 获取指定位置的元素  
  15.      */  
  16.     public E get(int index) {  
  17.         try {  
  18.             return listIterator(index).next();  //此迭代器由子类LinkedList实现  
  19.         } catch (NoSuchElementException exc) {  
  20.             throw new IndexOutOfBoundsException("Index: "+index);  
  21.         }  
  22.     }  
  23.   
  24.     /** 
  25.      * 替换指定位置的元素,返回原来的元素 
  26.      */  
  27.     public E set(int index, E element) {  
  28.     try {  
  29.         ListIterator<E> e = listIterator(index);   //此迭代器由子类LinkedList实现  
  30.         E oldVal = e.next();  
  31.         e.set(element);  
  32.         return oldVal;  
  33.     } catch (NoSuchElementException exc) {  
  34.         throw new IndexOutOfBoundsException("Index: "+index);  
  35.     }  
  36.     }  
  37.   
  38.     /** 
  39.      * 在指定位置添加一元素,原来的元素以及其随后的元素后移一个位置 
  40.      */  
  41.     public void add(int index, E element) {  
  42.     try {  
  43.         listIterator(index).add(element);   //此迭代器由子类LinkedList实现  
  44.     } catch (NoSuchElementException exc) {  
  45.         throw new IndexOutOfBoundsException("Index: "+index);  
  46.     }  
  47.     }  
  48.   
  49.     /** 
  50.      *  
  51.      * 移除List指定位置的元素,把它后面的元素向左移 
  52.      * 返回移除的元素 
  53.      */  
  54.     public E remove(int index) {  
  55.     try {  
  56.         ListIterator<E> e = listIterator(index);   //此迭代器由子类LinkedList实现  
  57.         E outCast = e.next();  
  58.         e.remove();  
  59.         return outCast;  
  60.     } catch (NoSuchElementException exc) {  
  61.         throw new IndexOutOfBoundsException("Index: "+index);  
  62.     }  
  63.     }  
  64.   
  65.   
  66.     // Bulk Operations  
  67.   
  68.     /** 
  69.      *  
  70.      * 在指定位置添加指定集合c中的所有元素, 
  71.      * 把当前位置的元素及其随后的元素向后移 
  72.      */  
  73.     public boolean addAll(int index, Collection<? extends E> c) {  
  74.     try {  
  75.         boolean modified = false;  
  76.         ListIterator<E> e1 = listIterator(index);   //获取指定位置的List迭代器,调用next会返回index位置的元素  
  77.         Iterator<? extends E> e2 = c.iterator();  
  78.         while (e2.hasNext()) {  //遍历c  
  79.         e1.add(e2.next());  //在指定位置添加  
  80.         modified = true;  
  81.         }  
  82.         return modified;  
  83.     } catch (NoSuchElementException exc) {  
  84.         throw new IndexOutOfBoundsException("Index: "+index);  
  85.     }  
  86.     }  
  87.   
  88.   
  89.     // Iterators  
  90.   
  91.     /** 
  92.      * 返回的是AbstractList的new ListItr(0) 
  93.      * 但由于用父类的引用指向子类的对象,只能调用Iterator中的方法。 
  94.      * 我觉得这里直接调用AbstractList的iterator()方法就可以了 
  95.      * 这个地方AbstractList中实现的迭代器中的get(index)方法是由LinkedList实现的 
  96.      */  
  97.     public Iterator<E> iterator() {  
  98.         return listIterator();  
  99.     }  
  100.   
  101.     /** 
  102.      * 如果要获取ListIterator,则由子类LinkedList实现 
  103.      */  
  104.     public abstract ListIterator<E> listIterator(int index);  
  105. }  



六。AbstractMap
Java代码  收藏代码
  1. public abstract class AbstractMap<K, V> implements Map<K, V> {  
  2.     /** 
  3.      * Sole constructor. (For invocation by subclass constructors, typically 
  4.      * implicit.) 
  5.      */  
  6.     protected AbstractMap() {  
  7.     }  
  8.   
  9.     // Query Operations  
  10.     /** 
  11.      *  entrySet返回一个Entry类型的Set集合, 
  12.      *  此Entry对象保存key,value值,并实现了一些基本方法 
  13.      *  比如getKey,getValue,setValue,equals和hashCode方法 
  14.      */  
  15.     public int size() {     //Set<Map.Entry<Key,Value>>的长度  
  16.         return entrySet().size();  
  17.     }  
  18.   
  19.       
  20.     public boolean isEmpty() {  
  21.         return size() == 0;     //size为0集合为空  
  22.     }  
  23.   
  24.     /** 
  25.      * 检查map是否包含指定value 
  26.      */  
  27.     public boolean containsValue(Object value) {  
  28.         Iterator<Entry<K, V>> i = entrySet().iterator();//返回Set<Map.Entry<Key,Value>>集合的迭代器  
  29.         if (value == null) {  
  30.             while (i.hasNext()) {   //迭代  
  31.                 Entry<K, V> e = i.next();  
  32.                 if (e.getValue() == null)   //找到给定的value则返回true  
  33.                     return true;  
  34.             }  
  35.         } else {  
  36.             while (i.hasNext()) {  
  37.                 Entry<K, V> e = i.next();  
  38.                 if (value.equals(e.getValue()))  
  39.                     return true;  
  40.             }  
  41.         }  
  42.         return false;  
  43.     }  
  44.   
  45.     /** 
  46.      * 检查map中是否包含指定key,类似containsValue方法 
  47.      */  
  48.     public boolean containsKey(Object key) {  
  49.         Iterator<Map.Entry<K, V>> i = entrySet().iterator();  
  50.         if (key == null) {  
  51.             while (i.hasNext()) {  
  52.                 Entry<K, V> e = i.next();  
  53.                 if (e.getKey() == null)  
  54.                     return true;  
  55.             }  
  56.         } else {  
  57.             while (i.hasNext()) {  
  58.                 Entry<K, V> e = i.next();  
  59.                 if (key.equals(e.getKey()))  
  60.                     return true;  
  61.             }  
  62.         }  
  63.         return false;  
  64.     }  
  65.   
  66.     /** 
  67.      * 查找包含此key值的Entry对象,返回entry的value值 
  68.      */  
  69.     public V get(Object key) {  
  70.         Iterator<Entry<K, V>> i = entrySet().iterator();  
  71.         if (key == null) {  
  72.             while (i.hasNext()) {  
  73.                 Entry<K, V> e = i.next();  
  74.                 if (e.getKey() == null)  
  75.                     return e.getValue();  
  76.             }  
  77.         } else {  
  78.             while (i.hasNext()) {  
  79.                 Entry<K, V> e = i.next();  
  80.                 if (key.equals(e.getKey()))  
  81.                     return e.getValue();  
  82.             }  
  83.         }  
  84.         return null;  
  85.     }  
  86.   
  87.     // Modification Operations  
  88.   
  89.     /** 
  90.      * 此方法需由AbstractMap的子类实现 
  91.      */  
  92.     public V put(K key, V value) {  
  93.         throw new UnsupportedOperationException();  
  94.     }  
  95.   
  96.     /** 
  97.      * 通过key值查找对应Entry,移除此Entry,并返回它的value值 
  98.      */  
  99.     public V remove(Object key) {  
  100.         Iterator<Entry<K, V>> i = entrySet().iterator();  
  101.         Entry<K, V> correctEntry = null;  
  102.         if (key == null) {  
  103.             while (correctEntry == null && i.hasNext()) {  
  104.                 Entry<K, V> e = i.next();  
  105.                 if (e.getKey() == null)  
  106.                     correctEntry = e;   //保存找到的Entry对象  
  107.             }  
  108.         } else {  
  109.             while (correctEntry == null && i.hasNext()) {  
  110.                 Entry<K, V> e = i.next();  
  111.                 if (key.equals(e.getKey()))  
  112.                     correctEntry = e;  
  113.             }  
  114.         }  
  115.   
  116.         V oldValue = null;  
  117.         if (correctEntry != null) {  
  118.             oldValue = correctEntry.getValue();  
  119.             i.remove();     //移除  
  120.         }  
  121.         return oldValue;  
  122.     }  
  123.   
  124.     // Bulk Operations  
  125.   
  126.     /** 
  127.      * 添加指定m中的所有键值对到本Map 
  128.      */  
  129.     public void putAll(Map<? extends K, ? extends V> m) {  
  130.         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())  
  131.             put(e.getKey(), e.getValue());  
  132.     }  
  133.   
  134.     /** 
  135.      * Set的clear方法 
  136.      */  
  137.     public void clear() {  
  138.         entrySet().clear();  
  139.     }  
  140.   
  141.     // Views  
  142.   
  143.     /** 
  144.      * 此变量不是持久化的,并且用volatile修饰表明 
  145.      * 对这俩个变量的操作时线程安全的 
  146.      */  
  147.     transient volatile Set<K> keySet = null;  
  148.     transient volatile Collection<V> values = null;  
  149.   
  150.     /** 
  151.      * 返回一个Set的子类 
  152.      *  
  153.      * 此Set集合只在第一次调用keySet()时被创建,此后返回的都是同一个Set。 
  154.      * 此方法不是线程安全的,大量线程多次调用此方法返回的可能不是同一个Set(可能是重新new的) 
  155.      */  
  156.     public Set<K> keySet() {  
  157.         if (keySet == null) {   //在new的过程中,又调用了此方法可能又重新new了一个keySet  
  158.             keySet = new AbstractSet<K>() {       //需要实现iterator()与size()方法  
  159.                 public Iterator<K> iterator() {  
  160.                     return new Iterator<K>() {  
  161.                         private Iterator<Entry<K, V>> i = entrySet().iterator(); //其实是调用entrySet的迭代器。由Set的子类实现  
  162.   
  163.                         public boolean hasNext() {  
  164.                             return i.hasNext();  
  165.                         }  
  166.   
  167.                         public K next() {  
  168.                             return i.next().getKey();  
  169.                         }  
  170.   
  171.                         public void remove() {  
  172.                             i.remove();  
  173.                         }  
  174.                     };  
  175.                 }  
  176.   
  177.                 public int size() {  
  178.                     return AbstractMap.this.size();  
  179.                 }  
  180.   
  181.                 public boolean contains(Object k) {     //重写AbstractCollection的contains方法  
  182.                     return AbstractMap.this.containsKey(k);     //为map的containsKey方法  
  183.                 }  
  184.             };  
  185.         }  
  186.         return keySet;  
  187.     }  
  188.   
  189.     /** 
  190.      * 与上面keySet()方法类似,不过返回的是Collection的子类 
  191.      *  
  192.      */  
  193.     public Collection<V> values() {  
  194.         if (values == null) {  
  195.             values = new AbstractCollection<V>() {  
  196.                 public Iterator<V> iterator() {  
  197.                     return new Iterator<V>() {  
  198.                         private Iterator<Entry<K, V>> i = entrySet().iterator();  
  199.   
  200.                         public boolean hasNext() {  
  201.                             return i.hasNext();  
  202.                         }  
  203.   
  204.                         public V next() {  
  205.                             return i.next().getValue();  
  206.                         }  
  207.   
  208.                         public void remove() {  
  209.                             i.remove();  
  210.                         }  
  211.                     };  
  212.                 }  
  213.   
  214.                 public int size() {  
  215.                     return AbstractMap.this.size();  
  216.                 }  
  217.   
  218.                 public boolean contains(Object v) { //重写父类contains为Map.containsValue(v)  
  219.                     return AbstractMap.this.containsValue(v);  
  220.                 }  
  221.             };  
  222.         }  
  223.         return values;  
  224.     }  
  225.   
  226.     public abstract Set<Entry<K, V>> entrySet();   //此方法由其子类实现,如HashMap,HashTable等  
  227.   
  228.     // Comparison and hashing  
  229.   
  230.     /** 
  231.      *  
  232.      * 比较俩个map是否相等,如果给定对象o是一个Map,即实现了Map接口,并且 
  233.      * 2个map含有同样的键值对,则它们相等。 
  234.      * 更正式的来说,返回结果为m1.entrySet().equals(m2.entrySet()) 
  235.      */  
  236.     public boolean equals(Object o) {  
  237.         if (o == this)      //如果是本map  
  238.             return true;  
  239.   
  240.         if (!(o instanceof Map))  //是否实现了Map接口  
  241.             return false;  
  242.         Map<K, V> m = (Map<K, V>) o;  
  243.         if (m.size() != size())     //键值对个数是否相等  
  244.             return false;  
  245.   
  246.         try {  
  247.             Iterator<Entry<K, V>> i = entrySet().iterator();  
  248.             while (i.hasNext()) {  
  249.                 Entry<K, V> e = i.next();  
  250.                 K key = e.getKey();  
  251.                 V value = e.getValue();  
  252.                 if (value == null) {  
  253.                     if (!(m.get(key) == null && m.containsKey(key)))    //如果m中有这个key并且相应value值为空则返回true  
  254.                         return false;  
  255.                 } else {  
  256.                     if (!value.equals(m.get(key)))  //m中根据key值找到的value与此value相等则返回ture  
  257.                         return false;  
  258.                 }  
  259.             }  
  260.         } catch (ClassCastException unused) {  
  261.             return false;  
  262.         } catch (NullPointerException unused) {  
  263.             return false;  
  264.         }  
  265.   
  266.         return true;          
  267.     }  
  268.   
  269.     /** 
  270.      *  
  271.      * entrySet中各个Entry的hashCode之和 
  272.      */  
  273.     public int hashCode() {  
  274.         int h = 0;  
  275.         Iterator<Entry<K, V>> i = entrySet().iterator();  
  276.         while (i.hasNext())  
  277.             h += i.next().hashCode();   //Entry的hashCode  
  278.         return h;  
  279.     }  
  280.   
  281.     /** 
  282.      * map的toString方法,返回类似{key1=value1, key2=value2, ....} 
  283.      */  
  284.     public String toString() {  
  285.         Iterator<Entry<K, V>> i = entrySet().iterator();  
  286.         if (!i.hasNext())  
  287.             return "{}";  
  288.   
  289.         StringBuilder sb = new StringBuilder();  
  290.         sb.append('{');  
  291.         for (;;) {  
  292.             Entry<K, V> e = i.next();  
  293.             K key = e.getKey();  
  294.             V value = e.getValue();  
  295.             sb.append(key == this ? "(this Map)" : key);  
  296.             sb.append('=');  
  297.             sb.append(value == this ? "(this Map)" : value);  
  298.             if (!i.hasNext())  
  299.                 return sb.append('}').toString();  
  300.             sb.append(", ");  
  301.         }  
  302.     }  
  303.   
  304.     /** 
  305.      * 
  306.      * 返回Map的浅拷贝对象,不拷贝key和value 
  307.      */  
  308.     protected Object clone() throws CloneNotSupportedException {  
  309.         AbstractMap<K, V> result = (AbstractMap<K, V>) super.clone();  
  310.         result.keySet = null;  
  311.         result.values = null;  
  312.         return result;  
  313.     }  
  314.   
  315.     /** 
  316.      *  
  317.      * 此方法非常实用,主要用于SimpleImmutableEntry与SimpleEntry中 
  318.      * 测试2个对象是否相等,是否为空. 
  319.      *  
  320.      */  
  321.     private static boolean eq(Object o1, Object o2) {  
  322.         return o1 == null ? o2 == null : o1.equals(o2);  
  323.     }  
  324.   
  325.   
  326.     /** 
  327.      * 
  328.      * 实现了Entry接口的类,用于保存key和value,并提供一些基础方法用于获取 
  329.      * key与value。可以使用setValue改变value的值 
  330.      *  
  331.      * @since 1.6 
  332.      */  
  333.     public static class SimpleEntry<K, V> implements Entry<K, V>,  
  334.             java.io.Serializable {  
  335.         private static final long serialVersionUID = -8499721149061103585L;  
  336.   
  337.         private final K key;  
  338.         private V value;  
  339.   
  340.         /** 
  341.          * 构造方法一,提供key和value 
  342.          */  
  343.         public SimpleEntry(K key, V value) {  
  344.             this.key = key;  
  345.             this.value = value;  
  346.         }  
  347.   
  348.         /** 
  349.          * 构造方法二,直接提供一个Entry对象 
  350.          */  
  351.         public SimpleEntry(Entry<? extends K, ? extends V> entry) {  
  352.             this.key = entry.getKey();  
  353.             this.value = entry.getValue();  
  354.         }  
  355.   
  356.         /** 
  357.          * 获取保存的key 
  358.          */  
  359.         public K getKey() {  
  360.             return key;  
  361.         }  
  362.   
  363.         /** 
  364.          * 获取保存的value 
  365.          */  
  366.         public V getValue() {  
  367.             return value;  
  368.         }  
  369.   
  370.         /** 
  371.          * 改变此entry对象的value值 
  372.          */  
  373.         public V setValue(V value) {  
  374.             V oldValue = this.value;  
  375.             this.value = value;  
  376.             return oldValue;  
  377.         }  
  378.   
  379.         /** 
  380.          *  
  381.          * 2个Entry对象判断相等的方法 
  382.          * (e1.getKey() == null ? e2.getKey() == null : e1.getKey().equals(e2.getKey())) 
  383.          *      && (e1.getValue() == null ? e2.getValue() == null : e1.getValue() 
  384.          *              .equals(e2.getValue())) 
  385.          */  
  386.         public boolean equals(Object o) {  
  387.             if (!(o instanceof Map.Entry))  //判断o是否实现了Map.Entry接口  
  388.                 return false;  
  389.             Map.Entry e = (Map.Entry) o;  
  390.             return eq(key, e.getKey()) && eq(value, e.getValue());  
  391.         }  
  392.   
  393.         /** 
  394.          * key的hashCode与value的hashCode异或 
  395.          */  
  396.         public int hashCode() {  
  397.             return (key == null ? 0 : key.hashCode())  
  398.                     ^ (value == null ? 0 : value.hashCode());  
  399.         }  
  400.   
  401.         /** 
  402.          * Entry的toString方法 
  403.          */  
  404.         public String toString() {    
  405.             return key + "=" + value;  
  406.         }  
  407.   
  408.     }  
  409.   
  410.     /** 
  411.      * 与SimpleEntry对象基本类似,只是SimpleImmutableEntry不支持setValue方法 
  412.      */  
  413.     public static class SimpleImmutableEntry<K, V> implements Entry<K, V>,  
  414.             java.io.Serializable {  
  415.         private static final long serialVersionUID = 7138329143949025153L;  
  416.   
  417.         private final K key;  
  418.         private final V value;  
  419.   
  420.           
  421.         public SimpleImmutableEntry(K key, V value) {  
  422.             this.key = key;  
  423.             this.value = value;  
  424.         }  
  425.   
  426.           
  427.         public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {  
  428.             this.key = entry.getKey();  
  429.             this.value = entry.getValue();  
  430.         }  
  431.   
  432.           
  433.         public K getKey() {  
  434.             return key;  
  435.         }  
  436.   
  437.           
  438.         public V getValue() {  
  439.             return value;  
  440.         }  
  441.   
  442.           
  443.         public V setValue(V value) {  
  444.             throw new UnsupportedOperationException();  
  445.         }  
  446.   
  447.           
  448.         public boolean equals(Object o) {  
  449.             if (!(o instanceof Map.Entry))  
  450.                 return false;  
  451.             Map.Entry e = (Map.Entry) o;  
  452.             return eq(key, e.getKey()) && eq(value, e.getValue());  
  453.         }  
  454.   
  455.           
  456.         public int hashCode() {  
  457.             return (key == null ? 0 : key.hashCode())  
  458.                     ^ (value == null ? 0 : value.hashCode());  
  459.         }  
  460.   
  461.         public String toString() {  
  462.             return key + "=" + value;  
  463.         }  
  464.   
  465.     }  
  466.   

原创粉丝点击