集合框架源码分析二(抽象类篇)
来源:互联网 发布:网络销售属于什么行业 编辑:程序博客网 时间:2024/06/05 14:47
一。AbstractCollection
二。AbstractList<E>
三。AbstractSet
四。AbstractQueue
五。AbstractSequentialList
六。AbstractMap
- 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;
- }
- }
- }
- 集合框架源码分析二(抽象类篇)
- 集合框架源码分析——抽象类
- java集合框架(二) Collection架构与源码分析
- Java 集合框架源码分析(二)——LinkedList
- Java 集合框架源码分析(二)——LinkedList
- Java 集合框架源码分析(二)——LinkedList
- 集合框架源码分析篇一(接口篇)
- 集合框架源码分析一(接口篇)
- Java集合源码分析(二)Linkedlist
- java集合框架11——TreeMap和源码分析(二)
- Java集合框架详解(二)——Collection源码分析
- 【Java集合类源码分析】HashMap源码分析二
- 【Java集合类源码分析】Java集合框架介绍
- 集合框架源码分析四(Collections类详细分析)
- 集合框架源码分析四(Collections类详细分析)
- JDK日志框架源码分析(二)
- skynet框架 源码分析 二
- min3d框架源码分析(二)
- session Replication & session sticky
- JSTL标签常用
- EL表达式详解教程
- Aptana 3 + XDebug 调试 PHP
- 集合框架源码分析篇一(接口篇)
- 集合框架源码分析二(抽象类篇)
- 关于基于RTGUI进行新UI开发的经历
- 集合框架源码分析三(实现类篇ArrayList,LinkedList,HashMap)
- 集合框架源码分析四(Collections类详细分析)
- 集合框架源码分析五之LinkedHashMap,LinkedHashSet
- 集合框架源码分析六之堆结构的实现(PriorityQueue)
- 13暑假集训#10 总结
- sgu 499 Greatest Greatest Common Divisor 约数“打表”
- HashMap的实现与优缺点