今天学习Java集合类中的一个抽象类,AbstractList

初识AbstractList

AbstractList 是一个抽象类,实现了List<E>接口,是隶属于Java集合框架中的 根接口 Collection 的分支,由其衍生的很多子类因为拥有强大的容器性能而被广泛应用,例如我们最为熟悉的ArrayList,这是它的类继承结构图:

特殊方法

AbstractList 虽然是抽象类,但其内部只有一个抽象方法 get():

abstract public E get(int index);

从字面上看这是获取的方法,子类必须实现它,一般是作为获取元素的用途,除此之外,如果子类要操作元素,还需要重写 add(), set(), remove() 方法,因为 AbstractList 虽然定义了这几个方法,但默认是不支持的,

public boolean add(E e) {
add(size(), e);
return true;
}
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}

可以看到,在其默认实现里,直接是抛出UnsupportedOperationException 异常的,这里的处理跟AbstractMap 的 put() 方法有异曲同工之妙处,很大功能就是官方考虑到也许会有子类需要这些方法不可修改,需要修改的话直接重写即可。

两个迭代器实现类

AbstractList 中提供了两个迭代器的实现类,默认实现了迭代器接口,实现了对元素的遍历,它们就是Itr 和其子类 ListItr,分别来了解一下。

先看Itr类,Itr 实现了 Iterator 接口,重写了 next() 和 remove() 方法,下面是它的源码:

private class Itr implements Iterator<E> {
//游标
int cursor;
//最近迭代的元素位置,每次使用完默认置为-1
int lastRet;
//记录容器被修改的次数,值不相等说明有并发操作
int expectedModCount = modCount; public boolean hasNext() {
return cursor != size();
} public E next() {
//检测是否有并发
checkForComodification(); try {
int i = cursor;
// 获取容器对应游标位置的元素
E next = get(i);
//记录获取到的元素的索引
lastRet = i;
//获取下一个元素的索引
cursor = i + 1;
return var2;
} catch (IndexOutOfBoundsException var3) {
this.checkForComodification();
throw new NoSuchElementException();
}
} public void remove() {
//还没读取元素就remove,报错
if (lastRet < 0) {
throw new IllegalStateException();
} else {
checkForComodification(); try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor) {
--this.cursor;
}
//删除后,把最后迭代的记录位置置为-1
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException var2) {
throw new ConcurrentModificationException();
}
}
}
//两个值不一致,说明有并发操作,抛出异常
final void checkForComodification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}

ListItr 是 Itr 的子类,在Itr 的基础上增强了对元素的操作,多了指定索引的赋值,以及向前读取,add 和 set 的方法。

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();
}
}
}

两个类的源码还是比较简单的,加了注释相信大家也能看出大概的逻辑。使用上,AbstractList类中提供了两个方法,返回的各自实现的接口类型对象:

public Iterator<E> iterator() {
return new Itr();
}
public ListIterator<E> listIterator() {
return listIterator(0);
}
public ListIterator<E> listIterator(final int index) {
rangeCheckForAdd(index); return new ListItr(index);
}

额。。。。。说错了,不是两个,是三个方法,懒得删,这句废话也加上吧。

获取对象索引

结合内部迭代器实现类,AbstractList 还提供了两个可以获取对象索引的方法,分别是

indexOf(): 获取指定对象 首次出现 的索引

public int indexOf(Object o) {
//返回迭代器类,此时默认游标位置是0
ListIterator<E> it = listIterator();
if (o==null) {
//向后遍历
while (it.hasNext())
//后面没元素了,返回游标前面元素的索引,这里为什么是返回前面索引呢?
//因为在ListIterator接口中,每次调用next()游标就会后移一位
//所以,当找到对应元素时,游标已经后移一位了,需要返回游标的前一个索引。
if (it.next()==null)
return it.previousIndex();
} else {
while (it.hasNext())
if (o.equals(it.next()))
return it.previousIndex();
}
return -1;
}

lastIndexOf() :获取指定对象最后一次出现的位置,原理和indexOf方法类似,只是改为后面向前

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;
}

两个子类

AbstractList 提供了两个子类,可用于切分集合序列,这两个类是 SubListRandomAccessSubList ,SubList 的内部实现和 AbstractList 很相似,无非是传递了两个变量,初识位置和结束位置来截取集合,具体原理就不做解析了,读者们自己看看吧,也不难,贴一下部分源码:

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);
}
............
............
}

RandomAccessSubList 是 SubList 的子类,内部实现直接沿用父类,只是实现了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);
}
}

不一样的是,RandomAccessSubList 实现了一个接口RandomAccess,打开后发现是空的,没有任何实现。

public interface RandomAccess {
}

它的作用是用于标识某个类是否支持 随机访问(随机访问,相对比“按顺序访问”)。一个支持随机访问的类明显可以使用更加高效的算法。例如遍历上,实现RandomAccess 接口的集合使用 get() 做迭代速度会更快,比起使用迭代器的话,

for (int i=0; i < list.size(); i++)
list.get(i);
 for (Iterator i=list.iterator(); i.hasNext();)
i.next();

例如ArrayList 就是实现了这个接口,而关于该接口有如此功效的原因这里暂且不做深入研究,日后有机会单独写一篇讲解下。

最后

作为抽象类,AbstractList本身算是定义比较完善的结构体系了,继承了它的衣钵的子类也拥有不俗的表现,在Java开发中被广泛应用,有时间的话打算多写几篇关于它的子类,好了,关于 AbstractList 的知识就学到这里了,睡觉了~

Java集合类源码解析:AbstractList的更多相关文章

  1. Java集合类源码解析:Vector

    [学习笔记]转载 Java集合类源码解析:Vector   引言 之前的文章我们学习了一个集合类 ArrayList,今天讲它的一个兄弟 Vector.为什么说是它兄弟呢?因为从容器的构造来说,Vec ...

  2. Java集合类源码解析:HashMap (基于JDK1.8)

    目录 前言 HashMap的数据结构 深入源码 两个参数 成员变量 四个构造方法 插入数据的方法:put() 哈希函数:hash() 动态扩容:resize() 节点树化.红黑树的拆分 节点树化 红黑 ...

  3. Java集合类源码解析:ArrayList

    目录 前言 源码解析 基本成员变量 添加元素 查询元素 修改元素 删除元素 为什么用 "transient" 修饰数组变量 总结 前言 今天学习一个Java集合类使用最多的类 Ar ...

  4. Java集合类源码解析:AbstractMap

    目录 引言 源码解析 抽象函数entrySet() 两个集合视图 操作方法 两个子类 参考: 引言 今天学习一个Java集合的一个抽象类 AbstractMap ,AbstractMap 是Map接口 ...

  5. Java集合类源码解析:LinkedHashMap

    前言 今天继续学习关于Map家族的另一个类 LinkedHashMap .先说明一下,LinkedHashMap 是继承于 HashMap 的,所以本文只针对 LinkedHashMap 的特性学习, ...

  6. 【转】Java HashMap 源码解析(好文章)

    ­ .fluid-width-video-wrapper { width: 100%; position: relative; padding: 0; } .fluid-width-video-wra ...

  7. JDK8集合类源码解析 - HashSet

    HashSet 特点:不允许放入重复元素 查看源码,发现HashSet是基于HashMap来实现的,对HashMap做了一次“封装”. private transient HashMap<E,O ...

  8. Java——LinkedHashMap源码解析

    以下针对JDK 1.8版本中的LinkedHashMap进行分析. 对于HashMap的源码解析,可阅读Java--HashMap源码解析 概述   哈希表和链表基于Map接口的实现,其具有可预测的迭 ...

  9. Java - TreeMap源码解析 + 红黑树

    Java提高篇(二七)-----TreeMap TreeMap的实现是红黑树算法的实现,所以要了解TreeMap就必须对红黑树有一定的了解,其实这篇博文的名字叫做:根据红黑树的算法来分析TreeMap ...

随机推荐

  1. Could not resolve placeholder 'IMAGE_SERVER_URL' in string value "${IMAGE_SERVER_URL}"

    这种问题 在网上查的是说使用了重复的property-placeholder   可能是在别的xml 也用了property-placeholder 解决方法 加上  ignore-unresolva ...

  2. C盘突然爆满

    C盘突然爆满!幸好还开的机!~~ 因为是突然就爆满了,想着应该是虚拟内存的原因!于是就开始了探索.... 1.文件夹选项中把所有文件都显示出来. 2.在C盘你就会看到一个“pagefile.sys”的 ...

  3. nginx配置ssl证书实现https访问

    一,环境说明 服务器系统:ubuntu16.04LTS 服务器IP地址:47.89.12.99 域名:bjubi.com 二,域名解析到服务器 在阿里云控制台-产品与服务-云解析DNS-找到需要解析的 ...

  4. 解决 spring-cloud-starter-zipkin 启动错误

    应用场景:Spring Boot 服务添加 Zipkin 依赖,进行服务调用的数据采集,然后进行 Zipkin-Server 服务调用追踪显示. 示例pom.xml配置: <parent> ...

  5. SUSE12Sp3安装配置.net core 生产环境(1)-IP,DNS,网关,SSH,GIT

    1.新增用户 sudo useradd 用户名 sudo passwd 用户名 这个时候会提示你输入密码,输入两次密码即可 2.静态 IP 设置 1.设置 IP 地址 sudo vi /etc/sys ...

  6. [Swift]LeetCode168. Excel表列名称 | Excel Sheet Column Title

    Given a positive integer, return its corresponding column title as appear in an Excel sheet. For exa ...

  7. [Swift]LeetCode391. 完美矩形 | Perfect Rectangle

    Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover o ...

  8. so库链接和运行时选择哪个路径下的库?

    总结今天遇到的一个so库链接.运行问题. 这几天修改了xapian的源码,重新编译so库,再重新编译之前的demo程序,跑起来后却发现执行的函数并非我修改过的,使用的还是老版本.折腾了一会儿,发现是因 ...

  9. 【java爬虫】---爬虫+基于接口的网络爬虫

    爬虫+基于接口的网络爬虫 上一篇讲了[java爬虫]---爬虫+jsoup轻松爬博客,该方式有个很大的局限性,就是你通过jsoup爬虫只适合爬静态网页,所以只能爬当前页面的所有新闻.如果需要爬一个网站 ...

  10. C#版 - Leetcode 201. 数字范围按位与(bitwise AND) - 题解

    C#版 - Leetcode 201. 数字范围按位与(bitwise AND) - 题解 在线提交: https://leetcode.com/problems/bitwise-and-of-num ...