`
zhouYunan2010
  • 浏览: 206407 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
社区版块
存档分类

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

阅读更多
一。AbstractCollection
public abstract class AbstractCollection<E> implements Collection<E> {
    /**
     * 唯一构造方法
     */
    protected AbstractCollection() {
    }

    // Query Operations

    /**
     *
     * 返回集合中元素的迭代器
     */
    public abstract Iterator<E> iterator();

    public abstract int size();

    public boolean isEmpty() {
	return size() == 0;   //size=0则此方法返回true
    }

    public boolean contains(Object o) {
	Iterator<E> e = iterator();   //获取此集合的迭代器
	if (o==null) {               
	    while (e.hasNext())      
		if (e.next()==null)   //如果此集合允许null元素,找到则返回true
		    return true;
	} else {
	    while (e.hasNext())
		if (o.equals(e.next()))
		    return true;
	}
	return false;
    }

    /**
     * 此方法是同步的,即使在遍历集合的过程中发现集合已经改变,任然可以返回
     * 正确的结果
     *
     * 此方法等同于:
     *
     * List<E> list = new ArrayList<E>(size());
     * for (E e : this)
     *     list.add(e);
     * return list.toArray();
     */
    public Object[] toArray() {
	Object[] r = new Object[size()]; //新建一个对象数组,长度为集合的长度
        Iterator<E> it = iterator();
	for (int i = 0; i < r.length; i++) {    //遍历赋值
	    if (! it.hasNext())	// 遍历过程中,集合中有元素被移除,长度减少
		return Arrays.copyOf(r, i);  //则仅返回长度为i的数组,i=当前集合长度
	    r[i] = it.next();
	}
        //如果遍历完后发现集合还有更多的元素,即在遍历时有元素被添加进集合,调用
        //finishToArray方法添加剩余的元素
	return it.hasNext() ? finishToArray(r, it) : r;
    }

   
    public <T> T[] toArray(T[] a) {
        int size = size();      //当前集合长度
        T[] r = a.length >= size ? a :  //如果a的长度大于等于size,把a赋给r,否则新建一个元素类型为a元素类型,size长度的数组
                  (T[])java.lang.reflect.Array
                  .newInstance(a.getClass().getComponentType(), size);
        Iterator<E> it = iterator();

	for (int i = 0; i < r.length; i++) {
	    if (! it.hasNext()) { 遍历过程中,集合中有元素被移除,长度减少.或遍历集合结束
		if (a != r)   //表明是新建的数组
		    return Arrays.copyOf(r, i);
		r[i] = null; // 表明是a,则多加一个null结束符
		return r;
	    }
	    r[i] = (T)it.next();
	}
	return it.hasNext() ? finishToArray(r, it) : r;
    }

    /**
     * 当it还有更多的元素,重新分配数组。并把剩余元素添加进数组
     */
   	private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
		int i = r.length;         //原来数组长度存入i中
		while (it.hasNext()) {
			int cap = r.length;   
			if (i == cap) {   //表明未重新分配数组长度
				int newCap = ((cap / 2) + 1) * 3;   //新数组长度的计算公式,大约扩充1.5倍
				if (newCap <= cap) { // 如果分配后发生了整型溢出
					if (cap == Integer.MAX_VALUE)
						throw new OutOfMemoryError("Required array size too large");
					newCap = Integer.MAX_VALUE;    
				}
				r = Arrays.copyOf(r, newCap); //新建一个长度为newCap的数组,并把r中数据存入
			}
			r[i++] = (T) it.next();   //添加集合剩余元素到新数组
		}
		// 修剪多余的长度
		return (i == r.length) ? r : Arrays.copyOf(r, i);
	}

    // Modification Operations

    /**
     * 调用此方法总是抛出一个异常,需要子类去重写此方法
     */
    public boolean add(E e) {
	throw new UnsupportedOperationException();
    }

    /**
     * 此方法会首先在集合中查找指定元素o,如果找到就移除它
     * 移除的是第一个找到的匹配的值
     */
    public boolean remove(Object o) {
	Iterator<E> e = iterator();
	if (o==null) {       //集合支持null元素
	    while (e.hasNext()) {
		if (e.next()==null) {
		    e.remove();     
		    return true;
		}
	    }
	} else {
	    while (e.hasNext()) {
		if (o.equals(e.next())) {
		    e.remove();
		    return true;
		}
	    }
	}
	return false;
    }


    // Bulk Operations

   
    public boolean containsAll(Collection<?> c) {
	Iterator<?> e = c.iterator();
	while (e.hasNext())
	    if (!contains(e.next()))  //如果c中有一个元素不在本集合中则返回false
		return false;
	return true;
    }

    /**
     * 此方法将抛出一个UnsupportedOperationException,除非子类重写了add方法
     */
    public boolean addAll(Collection<? extends E> c) {
	boolean modified = false;
	Iterator<? extends E> e = c.iterator();
	while (e.hasNext()) {
		if (add(e.next()))   //如果有一个元素添加失败就返回false
			modified = true;
	}
	return modified;
    }


    public boolean removeAll(Collection<?> c) {
	boolean modified = false;
	Iterator<?> e = iterator();
	while (e.hasNext()) {
		if (c.contains(e.next())) { //如果c中元素也保含在本集合中则移除它
			e.remove();
			modified = true;
		}
	}
	return modified;
	}

   public boolean retainAll(Collection<?> c) {
		boolean modified = false;
		Iterator<E> e = iterator();
		while (e.hasNext()) {
			if (!c.contains(e.next())) {  //遍历集合元素,如果元素不包含在c中,则移除此元素
				e.remove();               //取的是交集
				modified = true;
			}
		}
		return modified;
	}


    public void clear() {
	Iterator<E> e = iterator();
	while (e.hasNext()) {    //依次调用next和remove方法
	    e.next();
	    e.remove();
	}
    }


    //  String conversion

   /**
	 * 重写toString方法,返回格式:[e.toString, e2.toString, ...]
	 * */
	public String toString() {
		Iterator<E> i = iterator();
		if (!i.hasNext())   //如果集合为空返回[]
			return "[]";
		StringBuilder sb = new StringBuilder();
		sb.append('[');
		for (;;) {
			E e = i.next();
			sb.append(e == this ? "(this Collection)" : e);
			if (!i.hasNext())
				return sb.append(']').toString();
			sb.append(", ");
		}
	}

}



二。AbstractList<E>
public abstract class AbstractList<E> extends AbstractCollection<E> implements
		List<E> {
	/**
	 * 唯一构造方法
	 */
	protected AbstractList() {
	}

	/**
	 * 添加指定元素到List的最后
	 * 此方法将抛出一个UnsupportedOperationException除非List的子类重写了add(int,E)方法
	 * 
	 */
	public boolean add(E e) {
		add(size(), e);	//如果List子类没有重写此方法会抛出一个异常
		return true;
	}

	abstract public E get(int index);

	/**
	 * 总是抛出一个UnsupportedOperationException,除非子类重写了此方法
	 */
	public E set(int index, E element) {
		throw new UnsupportedOperationException();
	}

	/**
	 * 总是抛出一个UnsupportedOperationException,除非子类重写了此方法
	 */
	public void add(int index, E element) {
		throw new UnsupportedOperationException();
	}

	/**
	 * 总是抛出一个UnsupportedOperationException,除非子类重写了此方法
	 */
	public E remove(int index) {
		throw new UnsupportedOperationException();
	}

	// Search Operations
	
	public int indexOf(Object o) {
		ListIterator<E> e = listIterator();   //使用listIterator
		if (o == null) {
			while (e.hasNext())
				if (e.next() == null)
					return e.previousIndex();
		} else {
			while (e.hasNext())
				if (o.equals(e.next()))
					return e.previousIndex();
		}
		return -1;   //返回-1表示遍历到了集合最后都没有找到指定元素o
	}


	public int lastIndexOf(Object o) {
		ListIterator<E> e = listIterator(size());
		if (o == null) {
			while (e.hasPrevious())       //从后面开始遍历
				if (e.previous() == null)
					return e.nextIndex();
		} else {
			while (e.hasPrevious())
				if (o.equals(e.previous()))
					return e.nextIndex();
		}
		return -1;
	}

	// Bulk Operations

	public void clear() {
		removeRange(0, size());   //清空指定范围的元素
	}

	
	public boolean addAll(int index, Collection<? extends E> c) {
		boolean modified = false;
		Iterator<? extends E> e = c.iterator();
		while (e.hasNext()) {
			add(index++, e.next());  //把c中元素添加到指定位置,此add方法由子类实现
			modified = true;
		}
		return modified;
	}

	// Iterators


	public Iterator<E> iterator() {
		return new Itr();      //返回实现了Iterator接口的类
	}

	
	public ListIterator<E> listIterator() {
		return listIterator(0);   //返回一个listIterator,遍历起点为0
	}

	
	public ListIterator<E> listIterator(final int index) {
		if (index < 0 || index > size())       //index超出集合范围则抛出越界异常
			throw new IndexOutOfBoundsException("Index: " + index);

		return new ListItr(index);
	}
    
	/**
	 * 实现了Iterator接口中的所有方法
	 * */
	private class Itr implements Iterator<E> {
		/**
		 * 游标,随后调用next时返回的元素的索引
		 */
		int cursor = 0;

		/**
		 * 最近一次调用next或previous时返回的元素的索引
		 */
		int lastRet = -1;

		/**
         * 如果他们不相等说明迭代器检查到了并发操作
		 */
		int expectedModCount = modCount;

		public boolean hasNext() {
			return cursor != size();    //根据cursor大小来判断集合是否还有更多的元素
		}

		public E next() {
			checkForComodification();   //检测是否是并发操作
			try {
				E next = get(cursor);  //返回索引为cursor的元素
				lastRet = cursor++;    //调用next时cursor自增了
				return next;
			} catch (IndexOutOfBoundsException e) {  //如果索引超出集合边界则抛出IndexOutOfBoundsException
				checkForComodification();     //如果IndexOutOfBoundsException是由并发操作引起的则抛出NoSuchElementException
				throw new NoSuchElementException();
			}
		}

		public void remove() {
			if (lastRet == -1)   //这是为了判断是否调用了next方法
				throw new IllegalStateException();  //否则抛出IllegalStateException
			checkForComodification();   //同样要检查是否是并发操作

			try {
				AbstractList.this.remove(lastRet);  //迭代器的remove方法即是List的remove方法
				if (lastRet < cursor)  //在不断调用next方法时lastRet必然小于cursor,删除lastRet位置元素后cursor--,lastRet复位
					cursor--;
				lastRet = -1;
				expectedModCount = modCount;   
			} catch (IndexOutOfBoundsException e) {
				throw new ConcurrentModificationException();
			}
		}

		final void checkForComodification() {
			if (modCount != expectedModCount)
				throw new ConcurrentModificationException();
		}
	}

	private class ListItr extends Itr implements ListIterator<E> {
		ListItr(int index) {    //构造函数,传进cursor
			cursor = index;
		}

		public boolean hasPrevious() {    //当前cursor不为0则有前驱
			return cursor != 0;
		}

		public E previous() {  //前驱元素的索引为cursor-1
			checkForComodification();
			try {
				int i = cursor - 1;
				E previous = get(i);
				lastRet = cursor = i;   //lastRet为返回元素的索引
				return previous;
			} catch (IndexOutOfBoundsException e) {
				checkForComodification();
				throw new NoSuchElementException();
			}
		}

		public int nextIndex() {  //下一次调用next返回的元素的索引,即为cursor
			return cursor;
		}

		public int previousIndex() { //下一次调用previous方法返回的元素的索引
			return cursor - 1;
		}

		public void set(E e) {
			if (lastRet == -1)	//表明没有调用next或previous方法
				throw new IllegalStateException();
			checkForComodification();

			try {
				AbstractList.this.set(lastRet, e);    //lastRet为修改元素的索引
				expectedModCount = modCount;
			} catch (IndexOutOfBoundsException ex) {
				throw new ConcurrentModificationException();
			}
		}

		public void add(E e) {
			checkForComodification();

			try {
				AbstractList.this.add(cursor++, e);   //将元素e插入到调用next方法返回的元素之后,或者调用previous方法返回的元素之前
				lastRet = -1;		//重置lastRet
				expectedModCount = modCount;
			} catch (IndexOutOfBoundsException ex) {
				throw new ConcurrentModificationException();
			}
		}
	}

	/**
	 * new RandomAccessSubList<E>与new SubList<E>的区别是返回的子集合是否实现了RandomAccess
	 * 返回的是一个新的subList类,该类继承自AbstractList,实现了AbstractList的所有行为
	 */
	public List<E> subList(int fromIndex, int toIndex) {
		return (this instanceof RandomAccess ? new RandomAccessSubList<E>(this,
				fromIndex, toIndex) : new SubList<E>(this, fromIndex, toIndex));
	}

	// Comparison and hashing

	
	public boolean equals(Object o) {
		if (o == this)			 //o为本集合返回true
			return true; 
		if (!(o instanceof List))   //如果o没有实现List接口直接返回false
			return false;

		ListIterator<E> e1 = listIterator();
		ListIterator e2 = ((List) o).listIterator();
		while (e1.hasNext() && e2.hasNext()) {   //按位序依次遍历比较
			E o1 = e1.next();
			Object o2 = e2.next();
			if (!(o1 == null ? o2 == null : o1.equals(o2))) //比较o1与o2,不相等则返回flase
				return false;
		}
		//检查长度是否相等
		return !(e1.hasNext() || e2.hasNext());   
	}

	
	public int hashCode() {
		int hashCode = 1;
		Iterator<E> i = iterator();
		while (i.hasNext()) {
			E obj = i.next();
			//List hashCode的 计算公式
			hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
		}
		return hashCode;
	}

	/**
	 * 
	 * 移除指定范围的元素,左移随后的元素,并减少它们的索引
	 * 如果toIndex=fromIndex,此操作无影响
	 * 
	 */
	protected void removeRange(int fromIndex, int toIndex) {
		ListIterator<E> it = listIterator(fromIndex);	//是迭代器定位到fromIndex位置
		for (int i = 0, n = toIndex - fromIndex; i < n; i++) {   //移除toIndex - fromIndex个数元素
			it.next();
			it.remove();
		}
	}

	/**
	 * 此变量是用来检查iterator中的同步,在所有的对List的结构性操作中
	 * 此modCount的值都会加1,比如add()、remove()、addAll()、clear()等
	 */
	protected transient int modCount = 0;
}


/**
 * 主要功能用于获取集合完整结构的子范围,
 * 该类继承自AbstractList,拥有AbstractList中的所有操作
 * 对子范围进行操作会影响AbstractList,因为AbstractList被作为参数传进
 * 了SubList<E>,对SubList的操作其实是对AbstractList的操作
 * */
class SubList<E> extends AbstractList<E> {
	private AbstractList<E> l;
	private int offset;
	private int size;
	private int expectedModCount;

	SubList(AbstractList<E> list, int fromIndex, int toIndex) {   //初始化
		if (fromIndex < 0)
			throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
		if (toIndex > list.size())
			throw new IndexOutOfBoundsException("toIndex = " + toIndex);
		if (fromIndex > toIndex)
			throw new IllegalArgumentException("fromIndex(" + fromIndex
					+ ") > toIndex(" + toIndex + ")");
		l = list;
		offset = fromIndex;   //起始索引
		size = toIndex - fromIndex;  //子集长度
		expectedModCount = l.modCount;  //用于检查是否发生了并发操作
	}

	public E set(int index, E element) {
		rangeCheck(index);		//检查索引是否合法,即是否在0到size之间,不包含size
		checkForComodification();   
		return l.set(index + offset, element);  //对子集的操作其实是对原来集合的操作
	}

	public E get(int index) {
		rangeCheck(index);
		checkForComodification();
		return l.get(index + offset);
	}

	public int size() {
		checkForComodification();
		return size;
	}

	public void add(int index, E element) {
		if (index < 0 || index > size)   //可以等于size,表示添加 到最后
			throw new IndexOutOfBoundsException();
		checkForComodification();
		l.add(index + offset, element);
		expectedModCount = l.modCount;
		size++;
		modCount++;			//调用add方法集合结构发生改变时modCount++
	}

	public E remove(int index) {
		rangeCheck(index);
		checkForComodification();
		E result = l.remove(index + offset);
		expectedModCount = l.modCount;
		size--;
		modCount++;		// 调用remove方法集合结构发生改变时modCount++
		return result;
	}

	protected void removeRange(int fromIndex, int toIndex) {
		checkForComodification();
		l.removeRange(fromIndex + offset, toIndex + offset);
		expectedModCount = l.modCount;
		size -= (toIndex - fromIndex);	//size相应减少
		modCount++;			// 调用removeRange方法集合结构发生改变时modCount++
	}

	public boolean addAll(Collection<? extends E> c) {
		return addAll(size, c);		//在最后位置添加元素
	}

	public boolean addAll(int index, Collection<? extends E> c) {  //在指定位置添加元素
		if (index < 0 || index > size)
			throw new IndexOutOfBoundsException("Index: " + index + ", Size: "
					+ size);
		int cSize = c.size();
		if (cSize == 0)
			return false;

		checkForComodification();
		l.addAll(offset + index, c);
		expectedModCount = l.modCount;
		size += cSize;	//size相应增加
		modCount++;		// 调用addAll方法使集合结构发生改变时modCount++
		return true;
	}

	public Iterator<E> iterator() {
		return listIterator();
	}

	public ListIterator<E> listIterator(final int index) {
		checkForComodification();
		if (index < 0 || index > size)
			throw new IndexOutOfBoundsException("Index: " + index + ", Size: "
					+ size);

		/**
		 * 使用的还是父集合的listIterator方法
		 * 操作的实际是父元素
		 * */
		return new ListIterator<E>() {
			private ListIterator<E> i = l.listIterator(index + offset); //定位迭代器

			public boolean hasNext() {
				return nextIndex() < size;
			}

			public E next() {
				if (hasNext())
					return i.next();
				else
					throw new NoSuchElementException();
			}

			public boolean hasPrevious() {
				return previousIndex() >= 0;
			}

			public E previous() {
				if (hasPrevious())
					return i.previous();
				else
					throw new NoSuchElementException();
			}

			public int nextIndex() {	
				return i.nextIndex() - offset;
			}

			public int previousIndex() {
				return i.previousIndex() - offset;
			}

			public void remove() {
				i.remove();
				expectedModCount = l.modCount;
				size--;
				modCount++;  // 调用迭代器的remove方法使集合结构发生改变时modCount++
			}

			public void set(E e) {
				i.set(e);
			}

			public void add(E e) {
				i.add(e);
				expectedModCount = l.modCount;
				size++;
				modCount++; // 调用迭代器的add方法使集合结构发生改变时modCount++
			}
		};
	}

	public List<E> subList(int fromIndex, int toIndex) {  //subList的subList方法
		return new SubList<E>(this, fromIndex, toIndex);
	}

	private void rangeCheck(int index) {
		if (index < 0 || index >= size)
			throw new IndexOutOfBoundsException("Index: " + index + ",Size: "
					+ size);
	}

	private void checkForComodification() {
		if (l.modCount != expectedModCount)
			throw new ConcurrentModificationException();
	}
}

/**
 * 支持随机访问的RandomAccessSubList类需要实现RandomAccess接口和重写subList方法
 * 其他同SubList<E>类
 * */
class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
	RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
		super(list, fromIndex, toIndex);	
	}

	public List<E> subList(int fromIndex, int toIndex) {	//需重写其subList方法,也使其实现RandomAccess接口
		return new RandomAccessSubList<E>(this, fromIndex, toIndex);
	}
}



三。AbstractSet
public abstract class AbstractSet<E> extends AbstractCollection<E> implements
		Set<E> {
	/**
	 * 唯一构造器
	 */
	protected AbstractSet() {
	}

	// Comparison and hashing

	/**
	 *
	 */
	public boolean equals(Object o) {
		if (o == this)   //o就是本集合返回true
			return true;

		if (!(o instanceof Set))  //o不是一个Set,即没有实现Set接口,肯定返回false
			return false;
		Collection c = (Collection) o;	//这句话可能抛出ClassCastException
		if (c.size() != size())		//长度不等则返回false
			return false;
		try {
			return containsAll(c);	//如果c中元素都包含在本集合中则返回true
		} catch (ClassCastException unused) {
			return false;
		} catch (NullPointerException unused) {	  //o为空抛出NullPointerException
			return false;
		}
	}

	/**
	 * Set的hashCode值为所有元素的hashCode值之和
	 */
	public int hashCode() {
		int h = 0;
		Iterator<E> i = iterator();
		while (i.hasNext()) {
			E obj = i.next();
			if (obj != null)
				h += obj.hashCode();
		}
		return h;
	}

	/**
	 * 
	 * 移除Set中所有包含在c中的元素
	 * 此方法的实现原则是:如果Set含有更少的元素,就遍历set,依次检查每个迭代返回的
	 * 元素,看它是否包含在指定集合c中,如果包含就调用迭代器的remove方法移除它。
	 * 如果指定集合c含有更少的元素,就遍历c,调用Set的remove方法移除通过迭代器返回的元素
	 */
	public boolean removeAll(Collection<?> c) {
		boolean modified = false;

		if (size() > c.size()) {
			for (Iterator<?> i = c.iterator(); i.hasNext();)
				modified |= remove(i.next());   // |=表明只要一次remove方法返回true,modified就位true
		} else {
			for (Iterator<?> i = iterator(); i.hasNext();) {
				if (c.contains(i.next())) {
					i.remove();
					modified = true;
				}
			}
		}
		return modified;
	}

}



四。AbstractQueue
public abstract class AbstractQueue<E> extends AbstractCollection<E> implements
		Queue<E> {

	/**
	 * Constructor for use by subclasses.
	 */
	protected AbstractQueue() {
	}

	/**
	 * 此内部实现为offer方法,由其子类实现。
	 * 如果queue中有足够的容量则向其中插入e,否则抛出IllegalStateException
	 */
	public boolean add(E e) {
		if (offer(e))
			return true;
		else
			throw new IllegalStateException("Queue full");
	}

	/**
	 * 此内部实现为poll()方法,由其子类实现。
	 * poll方法返回不为空则表示移除头结点成功
	 * 否则抛出NoSuchElementException
	 */
	public E remove() {
		E x = poll();
		if (x != null)  //x为空则表示queue为空
			return x;
		else
			throw new NoSuchElementException();
	}

	/**
	 * 返回其头结点,但并不移除它
	 * 此方法内部由peek()实现,peek由其子类实现
	 * peek方法返回不为空则表示返回头结点成功,
	 * 否则抛出NoSuchElementException
	 */
	public E element() {
		E x = peek();
		if (x != null) //x为空则表示queue为空
			return x;
		else
			throw new NoSuchElementException();
	}

	/**
	 * 移除queue中所有元素
	 * 依次调用poll方法移除头结点
	 */
	public void clear() {
		while (poll() != null)
			;
	}

	/**
	 * 重写addAll方法
	 */
	public boolean addAll(Collection<? extends E> c) {
		if (c == null)	//queue不支持null元素
			throw new NullPointerException();
		if (c == this)
			throw new IllegalArgumentException();
		boolean modified = false;
		Iterator<? extends E> e = c.iterator();
		while (e.hasNext()) {
			if (add(e.next()))	//调用的是AbstractQueue的add方法,调用此方法可能抛出异常
				modified = true;
		}
		return modified;
	}

}



五。AbstractSequentialList
/**
 * 实现部分基础方法,使子类LinkedList不必再去实现
 * 实现了get,set,add,remove,addAll,iterator,listIterator方法
 * */
public abstract class AbstractSequentialList<E> extends AbstractList<E> {
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically
     * implicit.)
     */
    protected AbstractSequentialList() {
    }

    /**
     * 获取指定位置的元素 
     */
    public E get(int index) {
        try {
            return listIterator(index).next();  //此迭代器由子类LinkedList实现
        } catch (NoSuchElementException exc) {
            throw new IndexOutOfBoundsException("Index: "+index);
        }
    }

    /**
     * 替换指定位置的元素,返回原来的元素
     */
    public E set(int index, E element) {
	try {
	    ListIterator<E> e = listIterator(index);   //此迭代器由子类LinkedList实现
	    E oldVal = e.next();
	    e.set(element);
	    return oldVal;
	} catch (NoSuchElementException exc) {
	    throw new IndexOutOfBoundsException("Index: "+index);
	}
    }

    /**
     * 在指定位置添加一元素,原来的元素以及其随后的元素后移一个位置
     */
    public void add(int index, E element) {
	try {
	    listIterator(index).add(element);   //此迭代器由子类LinkedList实现
	} catch (NoSuchElementException exc) {
	    throw new IndexOutOfBoundsException("Index: "+index);
	}
    }

    /**
     * 
     * 移除List指定位置的元素,把它后面的元素向左移
     * 返回移除的元素
     */
    public E remove(int index) {
	try {
	    ListIterator<E> e = listIterator(index);   //此迭代器由子类LinkedList实现
	    E outCast = e.next();
	    e.remove();
	    return outCast;
	} catch (NoSuchElementException exc) {
	    throw new IndexOutOfBoundsException("Index: "+index);
	}
    }


    // Bulk Operations

    /**
     * 
     * 在指定位置添加指定集合c中的所有元素,
     * 把当前位置的元素及其随后的元素向后移
     */
    public boolean addAll(int index, Collection<? extends E> c) {
	try {
	    boolean modified = false;
	    ListIterator<E> e1 = listIterator(index);   //获取指定位置的List迭代器,调用next会返回index位置的元素
	    Iterator<? extends E> e2 = c.iterator();
	    while (e2.hasNext()) {	//遍历c
		e1.add(e2.next());	//在指定位置添加
		modified = true;
	    }
	    return modified;
	} catch (NoSuchElementException exc) {
	    throw new IndexOutOfBoundsException("Index: "+index);
	}
    }


    // Iterators

    /**
     * 返回的是AbstractList的new ListItr(0)
     * 但由于用父类的引用指向子类的对象,只能调用Iterator中的方法。
     * 我觉得这里直接调用AbstractList的iterator()方法就可以了
     * 这个地方AbstractList中实现的迭代器中的get(index)方法是由LinkedList实现的
     */
    public Iterator<E> iterator() {
        return listIterator();
    }

    /**
     * 如果要获取ListIterator,则由子类LinkedList实现
     */
    public abstract ListIterator<E> listIterator(int index);
}



六。AbstractMap
public abstract class AbstractMap<K, V> implements Map<K, V> {
	/**
	 * Sole constructor. (For invocation by subclass constructors, typically
	 * implicit.)
	 */
	protected AbstractMap() {
	}

	// Query Operations
    /**
     *  entrySet返回一个Entry类型的Set集合,
     *  此Entry对象保存key,value值,并实现了一些基本方法
     *  比如getKey,getValue,setValue,equals和hashCode方法
     */
	public int size() {		//Set<Map.Entry<Key,Value>>的长度
		return entrySet().size();
	}

	
	public boolean isEmpty() {
		return size() == 0;		//size为0集合为空
	}

	/**
	 * 检查map是否包含指定value
	 */
	public boolean containsValue(Object value) {
		Iterator<Entry<K, V>> i = entrySet().iterator();//返回Set<Map.Entry<Key,Value>>集合的迭代器
		if (value == null) {
			while (i.hasNext()) {	//迭代
				Entry<K, V> e = i.next();
				if (e.getValue() == null)  	//找到给定的value则返回true
					return true;
			}
		} else {
			while (i.hasNext()) {
				Entry<K, V> e = i.next();
				if (value.equals(e.getValue()))
					return true;
			}
		}
		return false;
	}

	/**
	 * 检查map中是否包含指定key,类似containsValue方法
	 */
	public boolean containsKey(Object key) {
		Iterator<Map.Entry<K, V>> i = entrySet().iterator();
		if (key == null) {
			while (i.hasNext()) {
				Entry<K, V> e = i.next();
				if (e.getKey() == null)
					return true;
			}
		} else {
			while (i.hasNext()) {
				Entry<K, V> e = i.next();
				if (key.equals(e.getKey()))
					return true;
			}
		}
		return false;
	}

	/**
	 * 查找包含此key值的Entry对象,返回entry的value值
	 */
	public V get(Object key) {
		Iterator<Entry<K, V>> i = entrySet().iterator();
		if (key == null) {
			while (i.hasNext()) {
				Entry<K, V> e = i.next();
				if (e.getKey() == null)
					return e.getValue();
			}
		} else {
			while (i.hasNext()) {
				Entry<K, V> e = i.next();
				if (key.equals(e.getKey()))
					return e.getValue();
			}
		}
		return null;
	}

	// Modification Operations

	/**
	 * 此方法需由AbstractMap的子类实现
	 */
	public V put(K key, V value) {
		throw new UnsupportedOperationException();
	}

	/**
	 * 通过key值查找对应Entry,移除此Entry,并返回它的value值
	 */
	public V remove(Object key) {
		Iterator<Entry<K, V>> i = entrySet().iterator();
		Entry<K, V> correctEntry = null;
		if (key == null) {
			while (correctEntry == null && i.hasNext()) {
				Entry<K, V> e = i.next();
				if (e.getKey() == null)
					correctEntry = e;	//保存找到的Entry对象
			}
		} else {
			while (correctEntry == null && i.hasNext()) {
				Entry<K, V> e = i.next();
				if (key.equals(e.getKey()))
					correctEntry = e;
			}
		}

		V oldValue = null;
		if (correctEntry != null) {
			oldValue = correctEntry.getValue();
			i.remove();		//移除
		}
		return oldValue;
	}

	// Bulk Operations

	/**
	 * 添加指定m中的所有键值对到本Map
	 */
	public void putAll(Map<? extends K, ? extends V> m) {
		for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
			put(e.getKey(), e.getValue());
	}

	/**
	 * Set的clear方法
	 */
	public void clear() {
		entrySet().clear();
	}

	// Views

	/**
	 * 此变量不是持久化的,并且用volatile修饰表明
	 * 对这俩个变量的操作时线程安全的
	 */
	transient volatile Set<K> keySet = null;
	transient volatile Collection<V> values = null;

	/**
	 * 返回一个Set的子类
	 * 
	 * 此Set集合只在第一次调用keySet()时被创建,此后返回的都是同一个Set。
	 * 此方法不是线程安全的,大量线程多次调用此方法返回的可能不是同一个Set(可能是重新new的)
	 */
	public Set<K> keySet() {
		if (keySet == null) {	//在new的过程中,又调用了此方法可能又重新new了一个keySet
			keySet = new AbstractSet<K>() {		//需要实现iterator()与size()方法
				public Iterator<K> iterator() {
					return new Iterator<K>() {
						private Iterator<Entry<K, V>> i = entrySet().iterator(); //其实是调用entrySet的迭代器。由Set的子类实现

						public boolean hasNext() {
							return i.hasNext();
						}

						public K next() {
							return i.next().getKey();
						}

						public void remove() {
							i.remove();
						}
					};
				}

				public int size() {
					return AbstractMap.this.size();
				}

				public boolean contains(Object k) {		//重写AbstractCollection的contains方法
					return AbstractMap.this.containsKey(k);		//为map的containsKey方法
				}
			};
		}
		return keySet;
	}

	/**
	 * 与上面keySet()方法类似,不过返回的是Collection的子类
	 * 
	 */
	public Collection<V> values() {
		if (values == null) {
			values = new AbstractCollection<V>() {
				public Iterator<V> iterator() {
					return new Iterator<V>() {
						private Iterator<Entry<K, V>> i = entrySet().iterator();

						public boolean hasNext() {
							return i.hasNext();
						}

						public V next() {
							return i.next().getValue();
						}

						public void remove() {
							i.remove();
						}
					};
				}

				public int size() {
					return AbstractMap.this.size();
				}

				public boolean contains(Object v) {	//重写父类contains为Map.containsValue(v)
					return AbstractMap.this.containsValue(v);
				}
			};
		}
		return values;
	}

	public abstract Set<Entry<K, V>> entrySet();   //此方法由其子类实现,如HashMap,HashTable等

	// Comparison and hashing

	/**
	 * 
	 * 比较俩个map是否相等,如果给定对象o是一个Map,即实现了Map接口,并且
	 * 2个map含有同样的键值对,则它们相等。
	 * 更正式的来说,返回结果为m1.entrySet().equals(m2.entrySet())
	 */
	public boolean equals(Object o) {
		if (o == this)		//如果是本map
			return true;

		if (!(o instanceof Map))  //是否实现了Map接口
			return false;
		Map<K, V> m = (Map<K, V>) o;
		if (m.size() != size())		//键值对个数是否相等
			return false;

		try {
			Iterator<Entry<K, V>> i = entrySet().iterator();
			while (i.hasNext()) {
				Entry<K, V> e = i.next();
				K key = e.getKey();
				V value = e.getValue();
				if (value == null) {
					if (!(m.get(key) == null && m.containsKey(key)))	//如果m中有这个key并且相应value值为空则返回true
						return false;
				} else {
					if (!value.equals(m.get(key)))	//m中根据key值找到的value与此value相等则返回ture
						return false;
				}
			}
		} catch (ClassCastException unused) {
			return false;
		} catch (NullPointerException unused) {
			return false;
		}

		return true;		
	}

	/**
	 * 
	 * entrySet中各个Entry的hashCode之和
	 */
	public int hashCode() {
		int h = 0;
		Iterator<Entry<K, V>> i = entrySet().iterator();
		while (i.hasNext())
			h += i.next().hashCode();	//Entry的hashCode
		return h;
	}

	/**
	 * map的toString方法,返回类似{key1=value1, key2=value2, ....}
	 */
	public String toString() {
		Iterator<Entry<K, V>> i = entrySet().iterator();
		if (!i.hasNext())
			return "{}";

		StringBuilder sb = new StringBuilder();
		sb.append('{');
		for (;;) {
			Entry<K, V> e = i.next();
			K key = e.getKey();
			V value = e.getValue();
			sb.append(key == this ? "(this Map)" : key);
			sb.append('=');
			sb.append(value == this ? "(this Map)" : value);
			if (!i.hasNext())
				return sb.append('}').toString();
			sb.append(", ");
		}
	}

	/**
	 *
	 * 返回Map的浅拷贝对象,不拷贝key和value
	 */
	protected Object clone() throws CloneNotSupportedException {
		AbstractMap<K, V> result = (AbstractMap<K, V>) super.clone();
		result.keySet = null;
		result.values = null;
		return result;
	}

	/**
	 * 
	 * 此方法非常实用,主要用于SimpleImmutableEntry与SimpleEntry中
	 * 测试2个对象是否相等,是否为空.
	 * 
	 */
	private static boolean eq(Object o1, Object o2) {
		return o1 == null ? o2 == null : o1.equals(o2);
	}


	/**
	 *
	 * 实现了Entry接口的类,用于保存key和value,并提供一些基础方法用于获取
	 * key与value。可以使用setValue改变value的值
	 * 
	 * @since 1.6
	 */
	public static class SimpleEntry<K, V> implements Entry<K, V>,
			java.io.Serializable {
		private static final long serialVersionUID = -8499721149061103585L;

		private final K key;
		private V value;

		/**
		 * 构造方法一,提供key和value
		 */
		public SimpleEntry(K key, V value) {
			this.key = key;
			this.value = value;
		}

		/**
		 * 构造方法二,直接提供一个Entry对象
		 */
		public SimpleEntry(Entry<? extends K, ? extends V> entry) {
			this.key = entry.getKey();
			this.value = entry.getValue();
		}

		/**
		 * 获取保存的key
		 */
		public K getKey() {
			return key;
		}

		/**
		 * 获取保存的value
		 */
		public V getValue() {
			return value;
		}

		/**
		 * 改变此entry对象的value值
		 */
		public V setValue(V value) {
			V oldValue = this.value;
			this.value = value;
			return oldValue;
		}

		/**
		 * 
		 * 2个Entry对象判断相等的方法
		 * (e1.getKey() == null ? e2.getKey() == null : e1.getKey().equals(e2.getKey()))
		 * 		&& (e1.getValue() == null ? e2.getValue() == null : e1.getValue()
		 * 				.equals(e2.getValue()))
		 */
		public boolean equals(Object o) {
			if (!(o instanceof Map.Entry))	//判断o是否实现了Map.Entry接口
				return false;
			Map.Entry e = (Map.Entry) o;
			return eq(key, e.getKey()) && eq(value, e.getValue());
		}

		/**
		 * key的hashCode与value的hashCode异或
		 */
		public int hashCode() {
			return (key == null ? 0 : key.hashCode())
					^ (value == null ? 0 : value.hashCode());
		}

		/**
		 * Entry的toString方法
		 */
		public String toString() {	
			return key + "=" + value;
		}

	}

	/**
	 * 与SimpleEntry对象基本类似,只是SimpleImmutableEntry不支持setValue方法
	 */
	public static class SimpleImmutableEntry<K, V> implements Entry<K, V>,
			java.io.Serializable {
		private static final long serialVersionUID = 7138329143949025153L;

		private final K key;
		private final V value;

		
		public SimpleImmutableEntry(K key, V value) {
			this.key = key;
			this.value = value;
		}

		
		public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {
			this.key = entry.getKey();
			this.value = entry.getValue();
		}

		
		public K getKey() {
			return key;
		}

		
		public V getValue() {
			return value;
		}

		
		public V setValue(V value) {
			throw new UnsupportedOperationException();
		}

		
		public boolean equals(Object o) {
			if (!(o instanceof Map.Entry))
				return false;
			Map.Entry e = (Map.Entry) o;
			return eq(key, e.getKey()) && eq(value, e.getValue());
		}

		
		public int hashCode() {
			return (key == null ? 0 : key.hashCode())
					^ (value == null ? 0 : value.hashCode());
		}

		public String toString() {
			return key + "=" + value;
		}

	}

}
分享到:
评论

相关推荐

    传智播客扫地僧视频讲义源码

    14_信息系统框架集成第三方产品案例_socket抽象类和框架搭建__传智扫地僧 15_信息系统框架集成第三方产品案例_框架实现第一个socket类厂商实现 16_信息系统框架集成第三方产品案例_第二个socket类厂商实现 17_信息...

    Java 知识汇总(资源,工具,笔记,源码,文章,文档分类整理).zip

    面向对象基本语法,抽象类,接口,内部类等;常用类api使用;常用算法,常用加密算法;Rxjava的使用;Http客户端接口测试,Okhttp的使用,HttpClient的使用,HttpUrlConnection的使用;集合的常见用法; 线程的基本知识;反射的...

    基于javatcpsocket通信的拆包和装包源码-java-interview:java基础知识点

    基于java tcp socket通信的拆包和装包源码 java-interview javac.exe&java.exe&javadoc.exe&PATH&CLASSPATH ...源码分析(集合&框架) 运行时数据区域 内存溢出 垃圾回收 垃圾收集器 类加载的过程 ComboBox(下拉列表框)

    asp.net知识库

    与DotNet数据对象结合的自定义数据对象设计 (二) 数据集合与DataTable 与DotNet数据对象结合的自定义数据对象设计 (一) 数据对象与DataRow ASP.NET中大结果集的分页[翻译] .net 2.0 访问Oracle --与Sql Server的...

    java基础案例与开发详解案例源码全

    11.1 Java集合框架概述264 11.2 Collection接口264 11.2 Set接口实现类266 11.2.1 实现类HashSet267 11.2.2 实现类LinkHashSet270 11.2.3 实现类TreeSet272 11.3 List接口实现类277 11.3.1 实现类ArrayList277 ...

    积分java源码-libsolace:关键系统的现代C++框架

    库:类型、函数、类等的集合,实现了一组设施(抽象),旨在潜在地用作多个程序的一部分。 从 这个库的想法部分受到 . 这就是使用现代 C++(至少C++17 )为高效和可靠的应用程序提供构建块的目的。 注意:它绝不是...

    单点登录源码

    Spring+SpringMVC+Mybatis框架集成公共模块,包括公共配置、MybatisGenerator扩展插件、通用BaseService、工具类等。 &gt; zheng-admin 基于bootstrap实现的响应式Material Design风格的通用后台管理系统,`zheng`...

    java范例开发大全(pdf&源码)

    第1篇 Java编程基础 第1章 Java开发环境的搭建(教学视频:9分钟) 2 1.1 理解Java 2 1.2 搭建Java所需环境 3 1.2.1 下载JDK 3 1.2.2 安装JDK 4 1.2.3 配置环境 5 1.2.4 测试JDK配置是否成功 7 实例1 开发第一个Java...

    java 面试题 总结

    声明方法的存在而不去实现它的类被叫做抽象类(abstract class),它用于要创建一个体现某些基本行为的类,并为该类声明方法,但不能在该类中实现该类的情况。不能创建abstract 类的实例。然而可以创建一个变量,其...

    外文翻译 stus MVC

    1:外文原文 Struts——an open-source MVC implementation This article introduces Struts, a Model-View-Controller implementation that uses servlets and JavaServer Pages (JSP) technology....

    大数据培训课程安排.pdf

    主要技术包括:java基础语法、java⾯向对象(类、对象、封装、继承、多态、 抽象类、接⼝、常见类、内部类、常见修饰符等) 、异常、集合、⽂件、IO、 MYSQL(基本SQL语句操作、多表查询、⼦查询、存储过程、事务、...

    超级有影响力霸气的Java面试题大全文档

     声明方法的存在而不去实现它的类被叫做抽象类(abstract class),它用于要创建一个体现某些基本行为的类,并为该类声明方法,但不能在该类中实现该类的情况。不能创建abstract 类的实例。然而可以创建一个变量,...

    Java范例开发大全(全书源程序)

    第12章 集合(教学视频:45分钟) 358 12.1 Set 358 实例204 利用HashSet删除学生 358 实例205 不重复的随机数序列 360 实例206 运用映射的相关类(Map) 363 实例207 运用集的相关类(Set) 365 12.2 List ...

Global site tag (gtag.js) - Google Analytics