二.Collection接口与抽象类

2017-09-08  本文已影响0人  蜗牛1991

1.层次图

image.png

2.接口Collection

3.AbstractCollection<E>

public boolean removeAll(Collection<?> c) {
          ....
        Iterator<?> it = iterator();//得到集合的迭代器
        while (it.hasNext())//判断是否有下个元素 {
            if (c.contains(it.next()))//得到下个元素 {
              .....
            }
        }
        return modified;
    }
    
 public <T> T[] toArray(T[] a) {
        // 若传入数组洗浴集合大小则反射创建集合大小的数组
        int size = size();
        T[] r = a.length >= size ? a :(T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
        .....
}
image.png

4.List与Set接口

5.java 设计思想一:

6.AbstractList

image.png
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
                      ......
    public Iterator<E> iterator() {
        return new Itr();
    }
    private class Itr implements Iterator<E> {
        //内部类方法调用
        public E next() {
            checkForComodification();
           //正常调用外部类方法,外部类调用内部类方法,内部类设为静态,或new内部类对象
            E next = get(i)
        }
                ....
      final void checkForComodification() { }
  }
    private class ListItr extends Itr implements ListIterator<E> { }
}
   public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof List))
            return false;
       return (this == o);
    }
    public int hashCode() {
        int hashCode = 1;
        for (E e : this){
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        }
        return hashCode;
    }
        //1.要拷贝复制的原始数据
        //2.原始数据的读取位置(从原始数据哪个位置开始拷贝)
        //3.存放要拷贝的原始数据的目的地
        //4.开始存放的位置()
        //5.要读取的原始数据长度(拷贝多长)
  System.arraycopy(elementData, index+1, elementData, index, numMoved);
每一个迭代器保存cursor,lastRet,expectedModCount三个变量。
cursor初始为0,对于每次调用next方法就增加一次,表示迭代的当前位置。
lastRet:保存了每次跳过的元素的坐标,用于迭代remove操作;
expectedModCount:记录这个迭代器对对象进行结构性修改的次数。这样每次迭代器进结构性修改的时候都将expectedModCount 和modCount进行对比,如果两种相等则说明没有其他迭代器修改了对象,可以进行。如果不相等则说明有迭代进行了修改,立刻抛出异常。

7.AbstractSet

image.png
上一篇下一篇

猜你喜欢

热点阅读