AbstractList
AbstractList是什么?
AbstractList是AbstractCollection和List的抽象子类,为一些通用的方法提供实现,并为所有List结构提供统一父类
继承结构
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { }
构造函数
protected AbstractList() { }
操作集合元素
添加元素
- add(int index, E element)抛出异常避免向AbstractList添加元素,其应由子类实现
- add(E e)默认添加在尾部
- addAll在指定位置添加传入的集合
public void add(int index, E element) { throw new UnsupportedOperationException(); } public boolean add(E e) { add(size(), e); return true; } 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; } 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(); }
获取元素
get()方法通过索引获取值
abstract public E get(int index);
设置元素
set()抛出异常避免向AbstractList设置元素
public E set(int index, E element) { throw new UnsupportedOperationException(); }
删除元素
remove()抛出异常避免从AbstractList删除元素
public E remove(int index) { throw new UnsupportedOperationException(); }
clear()方法边迭代边删除
public void clear() { removeRange(0, size()); } 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(); } }
获取下标
indexOf()从前往后遍历查找,lastIndexOf()从后往前遍历查找(可找null)
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; } 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; }
equals和hashCode
equals方法具体为:
- 先判断类地址是否相等
- 再判断是否是List子类,非List子类无listIterator
- 取出两者的listIterator循环比较其中的元素
- 若equals()方法执行过程中元素变多或变少则为false
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof List)) return false; ListIterator<E> e1 = listIterator(); ListIterator<?> e2 = ((List<?>) o