ArrayList源码解析(三)
1.isEmpty()
如果此列表中没有元素,则返回 true
/** * Returns <tt>true</tt> if this list contains no elements.*/ public boolean isEmpty() { return size == 0; }
判断ArrayList是否为空,size为0时,即不包含任何成员时为空,返回true。
2.indexOf(Objecto)
返回此列表中首次出现的指定元素的索引,或如果此列表不包含元素,则返回 -1。
public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; }
原理就是从前向后遍历数组,看其中是否有元素与所给的元素相等,有则返回索引。
3.lastIndexOf(Object o)
返回此列表中最后一次出现的指定元素的索引,或如果此列表不包含索引,则返回 -1。
public int lastIndexOf(Object o) { if (o == null) { for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = size-1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; }
此方法原理同IndexOf,只是从后向前遍历。
4.contains(Object o)
/** * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null ? e==null : o.equals(e))</tt>. * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(Object o) { return indexOf(o) >= 0; }
contains方法中调用indexOf方法,如果ArrayList中含有此元素,则IndexOf返回的索引值一定大于等于零。
5.clone()
返回此 ArrayList 实例的浅表副本。
/** * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The * elements themselves are not copied.) * * @return a clone of this <tt>ArrayList</tt> instance */ public Object clone() { try { ArrayList<?> v = (ArrayList<?>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } }
clone方法先调用根类Object的clone方法复制一个ArrayList v,然后将当前ArrayList的elementData复制到一个新数组,并让ArrayList v的elementData指向新数组。
因为v是新建立的,没有被修改过,modCount赋值为0。
注意,clone只是对ArrayList的浅复制,成员本身并没有被复制。
6.toArray()
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组
/** * Returns an array containing all of the elements in this list * in proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this list in * proper sequence */ public Object[] toArray() { return Arrays.copyOf(elementData, size); }
toArray()方法返回一个包含ArrayList所有元素的数组。该方法其实分配了一个新的Object数组,将elementData的成员复制到新的Object数组中,并将这个数组返回。
注意,ArrayList中没有指向toArray返回的数组的引用,调用者可以随意修改。
toArray方法充当着基于Array和基于Collection的APIs的桥梁。
7.toArray(T[] a)
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。
/** * Returns an array containing all of the elements in this list in proper * sequence (from first to last element); the runtime type of the returned * array is that of the specified array. If the list fits in the * specified array, it is returned therein. Otherwise, a new array is * allocated with the runtime type of the specified array and the size of * this list. * * <p>If the list fits in the specified array with room to spare * (i.e., the array has more elements than the list), the element in * the array immediately following the end of the collection is set to * <tt>null</tt>. (This is useful in determining the length of the * list <i>only</i> if the caller knows that the list does not contain * any null elements.) * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
这个方法是将ArrayList的所有元素拷贝到数组a中。
当ArrayList的size大于a的length时,也就是说a太小容纳不下ArrayList的所有元素,则调用Arrays.copyOf进行复制,这时不会再使用a,而是新开一个数组足够大的数组,将元素复制到新数组后将新数组返回。
如果a足够大可以容纳ArrayList的所有元素时,调用System.arraycopy进行复制,a的前size个位置是从ArrayList复制过来的元素,如果a.size==ArrayList.length,恰好装满,直接返回;如果a.size>ArrayList.length,则a[size]=null,表示结束。
8. elementData(int index)
// Positional Access Operations @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; }
elementData方法返回其内部数组elementData的index位置上的元素。
9.rangeCheck(int index)、 rangeCheckForAdd(int index)
/** * Checks if the given index is in range. If not, throws an appropriate * runtime exception. This method does *not* check if the index is * negative: It is always used immediately prior to an array access, * which throws an ArrayIndexOutOfBoundsException if index is negative. */ private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * A version of rangeCheck used by add and addAll. */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
rangeCheck方法其实就是检测index是否越界,ArrayList只有size个元素,index>=size时抛出越界异常。
rangeCheckForAdd()方法也是检测index是否越界,条件是index<0 || index >size。
值得注意的一点是rangeCheck和rangeCheckForAdd方法检测越界的提条件的差别:
rangeCheck供get、set和remove方法调用,这些都是在已经存在的元素上操作,范围自然是0到size-1;
rangeCheckForAdd方法由add方法调用,添加元素的位置可以是0到size-1,表示在元素中间插入,也可以是size,表示在所有元素之后插入。但是在大于size的位置插入时不可以,因为插入的元素和原有元素之间就留下了空档。
10.get(int index)
返回此列表中指定位置上的元素。
/** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { rangeCheck(index); return elementData(index); }
11.set(int index, E element)
用指定的元素替代此列表中指定位置上的元素。
/** * Replaces the element at the specified position in this list with * the specified element. * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
12.remvoe(int index)
移除此列表中指定位置上的元素
/** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; }
值得注意的是,当移除某个元素之后,它之后的所有元素都要向前移动一位,计算方式为 numMoved=size-index-1;
当index为size-1时,没有需要移动的元素;
numMoved>0时,调用System.arraycopy()方法移动元素,而且elementData[--size]=null,这里还将size减了1。
13.fastRemove(int index)
/* * Private remove method that skips bounds checking and does not * return the value removed. */ private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
fastRemove方法是私有的,仅供remove(Object o)方法调用。
fastRemove方法和remove(int index)方法的不同之处只在于fastRemove不进行边界检查,不返回值;因为fastRemove不需要这些功能。
14.remove(Object o)
移除此列表中首次出现的指定元素(如果存在)。
/** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }
方法移除ArrayList中出现的第一个元素o,采用遍历的方式获得要删除元素的索引index,然后调用fastRemove(int index)将其移除。
注意对元素o的判等方式,为null时使用==,否则使用equals方法。
15.removeRange(int fromIndex, int toIndex)
移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素。
/** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) * * @throws IndexOutOfBoundsException if {@code fromIndex} or * {@code toIndex} is out of range * ({@code fromIndex < 0 || * fromIndex >= size() || * toIndex > size() || * toIndex < fromIndex}) */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // clear to let GC do its work int newSize = size - (toIndex-fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; }
removeRange(int fromIndex, int toIndex)方法是移除list中fromIndex到toIndex之间的元素,注意包括fromIndex,但是不包括toIndex;
还要注意,fromIndex的合法取值为0到size-1,toIndex的合法取值为0到size,而且toIndex≥fromIndex;
当fromIndex==toIndex时, 此函数不做任何操作。
当移除n个元素之后,这之后的所有元素都要向前移动n位,计算方式为 numMoved=size-toIndex;
当toIndex为size时,没有需要移动的元素;
numMoved>0时,调用System.arraycopy()方法移动元素。
List的size变为newSize = size - (toIndex-fromIndex),并且elementData从newSize到size-1都要填充为null,最后size=newSize。
16.outOfBoundsMsg(int index)
/** * Constructs an IndexOutOfBoundsException detail message. * Of the many possible refactorings of the error handling code, * this "outlining" performs best with both server and client VMs. */ private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; }
此方法只是用来辅助在发生异常时输出越界信息的。
17.clear()
移除此列表中的所有元素。
/** * Removes all of the elements from this list. The list will * be empty after this call returns. */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }
clear方法比较简单,将所有的元素赋值为null即可。
18.removeAll(Collection<?> c)、retainAll(Collection<?> c)
前者移除ArrayList中那些也包含在指定 collection 中的所有元素(可选操作)。此调用返回后,collection 中将不包含任何与指定 collection 相同的元素。
后者仅保留ArrayList中那些也包含在指定 collection 的元素(可选操作)。换句话说,移除此 collection 中未包含在指定 collection 中的所有元素。
public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, false); } public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); }
这两个方法都是调用batchRemove实现:
batchRemove(c,false);
batchRemove(c,true);
不同的地方只有第二个参数一个为false,一个为true。
19.batchRemove(Collection<?> c, boolean complement)
实现移除或保留ArrayList中那些也包含在指定 collection 中的所有元素。
private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }
这个方法的重点在下面两句:
for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r];
当complement为true时,elementData中所有包含在c中的元素被保留了下来;
当complement为false时,elementData中所有未包含在c中的元素被保留了下来。
ArrayList源码解析(三)的更多相关文章
- Collection集合重难点梳理,增强for注意事项和三种遍历的应用场景,栈和队列特点,数组和链表特点,ArrayList源码解析, LinkedList-源码解析
重难点梳理 使用到的新单词: 1.collection[kəˈlekʃn] 聚集 2.empty[ˈempti] 空的 3.clear[klɪə(r)] 清除 4.iterator 迭代器 学习目标: ...
- ArrayList源码解析
ArrayList简介 ArrayList定义 1 public class ArrayList<E> extends AbstractList<E> implements L ...
- 顺序线性表 ---- ArrayList 源码解析及实现原理分析
原创播客,如需转载请注明出处.原文地址:http://www.cnblogs.com/crawl/p/7738888.html ------------------------------------ ...
- 面试必备:ArrayList源码解析(JDK8)
面试必备:ArrayList源码解析(JDK8) https://blog.csdn.net/zxt0601/article/details/77281231 概述很久没有写博客了,准确的说17年以来 ...
- 【源码解析】- ArrayList源码解析,绝对详细
ArrayList源码解析 简介 ArrayList是Java集合框架中非常常用的一种数据结构.继承自AbstractList,实现了List接口.底层基于数组来实现动态容量大小的控制,允许null值 ...
- Celery 源码解析三: Task 对象的实现
Task 的实现在 Celery 中你会发现有两处,一处位于 celery/app/task.py,这是第一个:第二个位于 celery/task/base.py 中,这是第二个.他们之间是有关系的, ...
- ArrayList源码解析(二)
欢迎转载,转载烦请注明出处,谢谢. https://www.cnblogs.com/sx-wuyj/p/11177257.html 自己学习ArrayList源码的一些心得记录. 继续上一篇,Arra ...
- Mybatis源码解析(三) —— Mapper代理类的生成
Mybatis源码解析(三) -- Mapper代理类的生成 在本系列第一篇文章已经讲述过在Mybatis-Spring项目中,是通过 MapperFactoryBean 的 getObject( ...
- Java中的容器(集合)之ArrayList源码解析
1.ArrayList源码解析 源码解析: 如下源码来自JDK8(如需查看ArrayList扩容源码解析请跳转至<Java中的容器(集合)>第十条):. package java.util ...
- ArrayList源码解析--值得深读
ArrayList源码解析 基于jdk1.8 ArrayList的定义 类注释 允许put null值,会自动扩容: size isEmpty.get.set.add等方法时间复杂度是O(1): 是非 ...
随机推荐
- SQL Server特殊用法笔记
1. MERGE用法:关联两表,有则改,无则加 SQL语句: create table #AAA(id int,A int,AA int,AAA int,B int) create table #BB ...
- VS 2017 Git failed with a fatal error的解决办法
前几天,满怀欣喜的从VS2015更新到了VS2017,经过这几天的试用,整体来说感觉还是挺不错的.昨天推送项目到远程服务器的时候,发现出现了推送失败的错误,错误如图: 按照提示,我看到输出窗口的输入内 ...
- java基础之类与对象3
前面我的两篇文章主要介绍了将怎么将事物抽象为对象,以及对象的实例化(就是new一个对象).这篇文章里面我就讲下匿名对象... 还是就举之前的例子把,Car c = new Car();看到这个我们就知 ...
- Node.js基本开发流程
创建一个hello world: 1.打开一个文本编辑器,在其中输入console.log("hello world"),并保存为hello.js; 注意:输入中文如果编码不是ut ...
- [原]使用MessageAnalyzer实时查看远端日志
1. 下载安装Message Analyzer 从Message Analyzer下载链接下载,安装过程从略. 说明:关于Message Analyzer的视频教程,可以在打开后的主界面上看到. 2. ...
- linux常用20命令 --转载
玩过Linux的人都会知道,Linux中的命令的确是非常多,但是玩过Linux的人也从来不会因为Linux的命令如此之多而烦恼,因为我们只需要掌握我们最常用的命令就可以了.当然你也可以在使用时去找一下 ...
- Java线程池(ThreadPool)详解
线程五个状态(生命周期): 线程运行时间 假设一个服务器完成一项任务所需时间为:T1 创建线程时间,T2 在线程中执行任务的时间,T3 销毁线程时间. 如果:T1 + T3 远大于 T2,则可以 ...
- OutOfMemoryError内存不足
java.lang.OutOfMemoryError内存不足错误.当可用内存不足以让Java虚拟机分配给一个对象时抛出该错误. 造成此错误的原因有一下几个: 1.内存中加载的数据量过于庞大,如一次从数 ...
- Map的迭代
public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Int ...
- C#邮件发送开发经本人测试通过
先准备以下工作 1.先开通邮箱我以QQ邮箱为例 2.开通 POP3/SMTP服务 (如何使用 Foxmail 等软件收发邮件?) 已开启 | 关闭 获取授权码 3.C#开发了先写一个CS文件 pub ...