java.util.Collection体系源码解读<四>AbstractList源码解读

package java.util;

/**
 * List 接口的骨干实现,分别有类ArrayList,Vector,内部类SubList,抽象类AbstractSequentialList实现了该接口
 * 。注意:对于连续的访问数据(如链表),应优先使用 AbstractSequentialList,而不是此类(jdk说明).
 * 要实现不可修改的列表,编程人员只需扩展此类,并提供 get(int) 和 size() 方法的实现。
 */
public abstract class AbstractList<E> extends AbstractCollection<E> implements
		List<E> {

	protected AbstractList() {
	}

	/** 将指定的元素添加到此列表的尾部,该方法需要具体的实现类去重写。 */
	public boolean add(E e) {
		add(size(), e);
		return true;
	}

	/** 按序号获取元素 */
	abstract public E get(int index);

	/** 待实现的在指定位置设置元素的方法 */
	public E set(int index, E element) {
		throw new UnsupportedOperationException();
	}

	/** 待实现的添加元素的方法 */
	public void add(int index, E element) {
		throw new UnsupportedOperationException();
	}

	/** 待实现, 删除指定位置的元素 */
	public E remove(int index) {
		throw new UnsupportedOperationException();
	}

	/**
	 * 返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1
	 * ,注意使用的是ListIterator,如果用hasNext(),则索引是值previousIndex
	 * (),按顺序搜索,自前向后,调用hasNext()
	 */
	public int indexOf(Object o) {
		ListIterator<E> it = listIterator();
		if (o == null) {
			while (it.hasNext())
				if (it.next() == null)
					return it.previousIndex();
		} else {
			while (it.hasNext())
				if (o.equals(it.next()))
					return it.previousIndex();
		}
		return -1;
	}

	/**
	 * 返回此列表中最后一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1 ,和indexOf(E e)逆向,这里迭代肯定只能用
	 * hasPrevious()了
	 */
	public int lastIndexOf(Object o) {
		ListIterator<E> it = listIterator(size());
		if (o == null) {
			while (it.hasPrevious())
				if (it.previous() == null)
					return it.nextIndex();
		} else {
			while (it.hasPrevious())
				if (o.equals(it.previous()))
					return it.nextIndex();
		}
		return -1;
	}

	/** 删除list中所有元素,这个方法调用 removeRange */
	public void clear() {
		removeRange(0, size());
	}

	/**
	 * 在指定集合中的所有元素进行迭代,并插入本list中,插入位置为指定的位置开始,如果原有位置有元素,那么原来该位置开始的所有元素将统一向后移动,注意
	 * : 插入的仅仅只是一个引用,并没有进行克隆
	 */
	public boolean addAll(int index, Collection<? extends E> c) {
		// 游标检查
		rangeCheckForAdd(index);
		boolean modified = false;
		for (E e : c) {
			add(index++, e);
			modified = true;
		}
		return modified;
	}

	/** 返回此列表的元素上进行迭代的通用Collection迭代器 */
	public Iterator<E> iterator() {
		return new Itr();
	}

	/** 返回此列表的元素上进行迭代的ListIterator迭代器 */
	public ListIterator<E> listIterator() {
		return listIterator(0);
	}

	/**
	 * 返回从指定位置起始的ListIterator迭代器,注意:指定的索引表示 next 的初始调用所返回的第一个元素。previous
	 * 方法的初始调用将返回索引比指定索引少 1 的元素,实际上次迭代器调用的是已经实现的内部迭代器ListItr
	 */
	public ListIterator<E> listIterator(final int index) {
		rangeCheckForAdd(index);
		return new ListItr(index);
	}

	/**
	 * 通用迭代器Iterator的第一个内部实现,用来聚集内部元素并访问,可称之为内聚子
	 */
	private class Itr implements Iterator<E> {
		// 下一个元素的游标,从起始位置开始
		int cursor = 0;
		// 上一次使用的游标 ,如果元素被删除或者不存在,返回-1
		int lastRet = -1;
		// 抛出异常的次数,默认为modCount(参考其说明),遍历过程中,如果进行修改,那么这个值将发生变化,进而抛出异常
		int expectedModCount = modCount;

		public boolean hasNext() {
			return cursor != size();
		}

		public E next() {
			// 检查list结构是否改变,如果改变将抛出 ConcurrentModificationException
			checkForComodification();
			try {
				int i = cursor;
				E next = get(i);
				lastRet = i;
				cursor = i + 1;
				return next;
			} catch (IndexOutOfBoundsException e) {
				checkForComodification();
				throw new NoSuchElementException();
			}
		}

		public void remove() {
			if (lastRet < 0)
				throw new IllegalStateException();
			checkForComodification();
			try {
				// 因为迭代时,已经迭代至下一个了,所以此处删除的是lastRet
				AbstractList.this.remove(lastRet);
				if (lastRet < cursor)
					cursor--;
				lastRet = -1;
				expectedModCount = modCount;
			} catch (IndexOutOfBoundsException e) {
				throw new ConcurrentModificationException();
			}
		}

		// 检查是否在迭代过程中,list的结构发生改变
		final void checkForComodification() {
			if (modCount != expectedModCount)
				throw new ConcurrentModificationException();
		}
	}

	/**
	 * 内聚子的派生类,也是对外提供的迭代器,新派生hasPrevious();previous();nextIndex();previousIndex(
	 * );set();add()等方法
	 */
	private class ListItr extends Itr implements ListIterator<E> {
		ListItr(int index) {
			cursor = index;
		}

		// 是否存在下一元素,逆序
		public boolean hasPrevious() {
			return cursor != 0;
		}

		// 逆向迭代
		public E previous() {
			checkForComodification();
			try {
				int i = cursor - 1;
				E previous = get(i);
				lastRet = cursor = i;
				return previous;
			} catch (IndexOutOfBoundsException e) {
				checkForComodification();
				throw new NoSuchElementException();
			}
		}

		public int nextIndex() {
			return cursor;
		}

		public int previousIndex() {
			return cursor - 1;
		}

		public void set(E e) {
			if (lastRet < 0)
				throw new IllegalStateException();
			checkForComodification();
			try {
				AbstractList.this.set(lastRet, e);
				expectedModCount = modCount;
			} catch (IndexOutOfBoundsException ex) {
				throw new ConcurrentModificationException();
			}
		}

		public void add(E e) {
			checkForComodification();
			try {
				int i = cursor;
				AbstractList.this.add(i, e);
				lastRet = -1;
				cursor = i + 1;
				expectedModCount = modCount;
			} catch (IndexOutOfBoundsException ex) {
				throw new ConcurrentModificationException();
			}
		}
	}

	/**
	 * List的截取方法, 返回列表中指定的 fromIndex(包括 )和
	 * toIndex(不包括)之间的部分视图,注意:1.这是一个前闭后开的区间,如果 fromIndex=toIndex,则返回空的List视图,2.
	 * 此截取方法返回的List是SubList或者RandomAccessSubList,这两个内部子表是不支持序列化的
	 */
	public List<E> subList(int fromIndex, int toIndex) {
		return (this instanceof RandomAccess ? new RandomAccessSubList<>(this,
				fromIndex, toIndex) : new SubList<>(this, fromIndex, toIndex));
	}

	/**
	 * 注意对象相等的条件:大小相同,顺序相同,元素相等,3个条件缺一不可
	 */
	public boolean equals(Object o) {
		if (o == this)
			return true;
		if (!(o instanceof List))
			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)))
				return false;
		}
		return !(e1.hasNext() || e2.hasNext());
	}

	/** 计算次list的hash码,计算方法为list中的每个元素的哈希吗*31加起来,null元素的哈希吗为0 */
	public int hashCode() {
		int hashCode = 1;
		for (E e : this)
			hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
		return hashCode;
	}

	/** 从指定位置到截止位置删除元素 (如果存在),前闭后开 */
	protected void removeRange(int fromIndex, int toIndex) {
		ListIterator<E> it = listIterator(fromIndex);
		for (int i = 0, n = toIndex - fromIndex; i < n; i++) {
			it.next();
			it.remove();
		}
	}

	/**
	 * 已从结构上修改 此列表的次数。从结构上修改是指更改列表的大小,或者打乱列表,从而使正在进行的迭代产生错误的结果,
	 * 如果意外更改了此字段中的值,则迭代器 (或列表迭代器)将抛出 ConcurrentModificationException 来响应
	 * next、remove、previous、set 或 add 操作。在迭代期间面临并发修改时,它提供了快速失败 行为,而不是非确定性行为。
	 */
	protected transient int modCount = 0;

	/** 下标越界异常加测 */
	private void rangeCheckForAdd(int index) {
		if (index < 0 || index > size())
			throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
	}

	private String outOfBoundsMsg(int index) {
		return "Index: " + index + ", Size: " + size();
	}
}

/**
 * 内部子表,用于截取list的一段,此list未进行序列化,可以看做是仅仅把起始位置和终止位置改变的一端list,其余方法不变
 */
class SubList<E> extends AbstractList<E> {
	private final AbstractList<E> l;
	// 偏移位置(起始位置)
	private final int offset;
	// 子表大小
	private int size;

	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;
		this.modCount = l.modCount;
	}

	public E set(int index, E element) {
		rangeCheck(index);
		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) {
		rangeCheckForAdd(index);
		checkForComodification();
		l.add(index + offset, element);
		this.modCount = l.modCount;
		size++;
	}

	public E remove(int index) {
		rangeCheck(index);
		checkForComodification();
		E result = l.remove(index + offset);
		this.modCount = l.modCount;
		size--;
		return result;
	}

	protected void removeRange(int fromIndex, int toIndex) {
		checkForComodification();
		l.removeRange(fromIndex + offset, toIndex + offset);
		this.modCount = l.modCount;
		size -= (toIndex - fromIndex);
	}

	public boolean addAll(Collection<? extends E> c) {
		return addAll(size, c);
	}

	public boolean addAll(int index, Collection<? extends E> c) {
		rangeCheckForAdd(index);
		int cSize = c.size();
		if (cSize == 0)
			return false;

		checkForComodification();
		l.addAll(offset + index, c);
		this.modCount = l.modCount;
		size += cSize;
		return true;
	}

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

	public ListIterator<E> listIterator(final int index) {
		checkForComodification();
		rangeCheckForAdd(index);

		return new ListIterator<E>() {
			private final 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();
				SubList.this.modCount = l.modCount;
				size--;
			}

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

			public void add(E e) {
				i.add(e);
				SubList.this.modCount = l.modCount;
				size++;
			}
		};
	}

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

	private void rangeCheck(int index) {
		if (index < 0 || index >= size)
			throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
	}

	private void rangeCheckForAdd(int index) {
		if (index < 0 || index > size)
			throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
	}

	private String outOfBoundsMsg(int index) {
		return "Index: " + index + ", Size: " + size;
	}

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

/**
 * 实现了RandomAccess接口的子表,其目的是:用来表示只是随机方法
 */
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) {
		return new RandomAccessSubList<>(this, fromIndex, toIndex);
	}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值