使用技巧:

将ArrayList转化为int数组

int[] ret = arr.stream().mapToInt(Integer::intValue).toArray();

一、参数

1.1 默认容量

/*** Default initial capacity.*/private static final int DEFAULT_CAPACITY = 10;

1.2 空数组

/*** Shared empty array instance used for empty instances.*/private static final Object[] EMPTY_ELEMENTDATA = {};

1.3 空初始化时的数组

/*** Shared empty array instance used for default sized empty instances. We* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when* first element is added.*/private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

1.4 存储数据的数组

/*** The array buffer into which the elements of the ArrayList are stored.* The capacity of the ArrayList is the length of this array buffer. Any* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA* will be expanded to DEFAULT_CAPACITY when the first element is added.*/transient Object[] elementData; // non-private to simplify nested class access

1.5 数组大小

/*** The size of the ArrayList (the number of elements it contains).** @serial*/private int size;

二、方法

2.1 add(添加元素)

/*** Appends the specified element to the end of this list.** @param e element to be appended to this list* @return <tt>true</tt> (as specified by {@link Collection#add})*/public boolean add(E e) {ensureCapacityInternal(size + 1);  // Increments modCount!!elementData[size++] = e;return true;}
/*** Inserts the specified element at the specified position in this* list. Shifts the element currently at that position (if any) and* any subsequent elements to the right (adds one to their indices).** @param index index at which the specified element is to be inserted* @param element element to be inserted* @throws IndexOutOfBoundsException {@inheritDoc}*/public void add(int index, E element) {rangeCheckForAdd(index);ensureCapacityInternal(size + 1);  // Increments modCount!!System.arraycopy(elementData, index, elementData, index + 1,size - index);elementData[index] = element;size++;}

2.1.1 ensureCapacityInternal

private void ensureCapacityInternal(int minCapacity) {ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));}

2.1.1.1 ensureExplicitCapacity

private void ensureExplicitCapacity(int minCapacity) {modCount++;// overflow-conscious codeif (minCapacity - elementData.length > 0)grow(minCapacity);}

2.1.1.2 calculateCapacity

private static int calculateCapacity(Object[] elementData, int minCapacity) {if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {return Math.max(DEFAULT_CAPACITY, minCapacity);}return minCapacity;}

2.2 grow(扩大数组容量)

扩大数组容量使得数组最少可以容纳由minCapacity指定的元素个数。

    private void grow(int minCapacity) {// overflow-conscious codeint oldCapacity = elementData.length;int newCapacity = oldCapacity + (oldCapacity >> 1);if (newCapacity - minCapacity < 0)newCapacity = minCapacity;if (newCapacity - MAX_ARRAY_SIZE > 0)newCapacity = hugeCapacity(minCapacity);// minCapacity is usually close to size, so this is a win:elementData = Arrays.copyOf(elementData, newCapacity);}

2.2.1 hugeCapacity

private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}

2.3 size

/*** Returns the number of elements in this list.** @return the number of elements in this list*/public int size() {return size;}

2.4 isEmpty

/*** Returns <tt>true</tt> if this list contains no elements.** @return <tt>true</tt> if this list contains no elements*/public boolean isEmpty() {return size == 0;}

2.5 contains

/*** 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&nbsp;?&nbsp;e==null&nbsp;:&nbsp;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;}

2.5.1 indexOf

/*** Returns the index of the first occurrence of the specified element* in this list, or -1 if this list does not contain the element.* More formally, returns the lowest index <tt>i</tt> such that* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,* or -1 if there is no such index.*/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;}

2.5.2 lastIndexOf

/*** Returns the index of the last occurrence of the specified element* in this list, or -1 if this list does not contain the element.* More formally, returns the highest index <tt>i</tt> such that* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,* or -1 if there is no such index.*/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;}

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

2.7 get

获取数据的时间复杂度是O(1)

/*** 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);}

2.7.1 rangeCheck

/*** 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));}

2.8 set

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

2.9 remove

删除数据的开销很大,因为要重排数组中的数据(在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 workreturn oldValue;}
/*** 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&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;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;}

2.9.1 fastRemove

/** 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}

2.10 构造方法

/*** Constructs an empty list with the specified initial capacity.** @param  initialCapacity  the initial capacity of the list* @throws IllegalArgumentException if the specified initial capacity*         is negative*/public ArrayList(int initialCapacity) {if (initialCapacity > 0) {this.elementData = new Object[initialCapacity];} else if (initialCapacity == 0) {this.elementData = EMPTY_ELEMENTDATA;} else {throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);}}
/*** Constructs an empty list with an initial capacity of ten.*/public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}
/*** Constructs a list containing the elements of the specified* collection, in the order they are returned by the collection's* iterator.** @param c the collection whose elements are to be placed into this list* @throws NullPointerException if the specified collection is null*/public ArrayList(Collection<? extends E> c) {elementData = c.toArray();if ((size = elementData.length) != 0) {// c.toArray might (incorrectly) not return Object[] (see 6260652)if (elementData.getClass() != Object[].class)elementData = Arrays.copyOf(elementData, size, Object[].class);} else {// replace with empty array.this.elementData = EMPTY_ELEMENTDATA;}}

jdk中ArrayList的实现相关推荐

  1. 那些jdk中坑你没商量的方法

    点击关注公众号,Java干货及时送达 来源:https://www.cnblogs.com/wyq178/p/13520745.html 前言 jdk作为我们每天必备的调用类库,里面大量提供了基础类供 ...

  2. JDK中的坑:JDK中这些方法的bug你不要踩

    点击关注公众号,Java干货及时送达 图片来源:白夜追凶 前言: jdk作为我们每天必备的调用类库,里面大量提供了基础类供我们使用.可以说离开jdk,我们的java代码寸步难行,jdk带给我们的便利可 ...

  3. 【并发编程】Future模式及JDK中的实现

    本文讲解Java中Future模式的使用,文章也发布在了公号(点击查看),欢迎交流. 1.1.Future模式是什么 先简单举个例子介绍,当我们平时写一个函数,函数里的语句一行行同步执行,如果某一行执 ...

  4. 惊呆了,JDK中这些常用方法也有Bug?

    点击上方 好好学java ,选择 星标 公众号重磅资讯,干货,第一时间送达 今日推荐:14 个 github 项目!个人原创100W +访问量博客:点击前往,查看更多 来源:cnblogs.com/w ...

  5. JDK中这些常用方法也有Bug

    点击上方"朱小厮的博客",选择"设为星标" 后台回复"书",获取 后台回复"k8s",可领取k8s资料 前言: jdk作 ...

  6. java stack 类 效率_Java中ArrayList、LinkedList、Vector、Stack的比较

    一.介绍 先回顾一下List的框架图 由图中的继承关系,可以知道,ArrayList.LinkedList.Vector.Stack都是List的四个实现类. AbstractList是一个抽象类,它 ...

  7. 【java】浅析JDK中ServiceLoader的源码

    1.概述 转载:浅析JDK中ServiceLoader的源码 上一篇文章:深入探讨 Java 类加载器 2.ServiceLoader的使用 这里先列举一个经典的例子,MySQL的Java驱动就是通过 ...

  8. 13万字详细分析JDK中Stream的实现原理

    前提 Stream是JDK1.8中首次引入的,距今已经过去了接近8年时间(JDK1.8正式版是2013年底发布的).Stream的引入一方面极大地简化了某些开发场景,另一方面也可能降低了编码的可读性( ...

  9. java基础巩固-宇宙第一AiYWM:为了维持生计,单例模式阅读总结【单例模式不同写法、在JDK中的应用】~整起

    无论是哪种设计模式,自己啃哪本书哪个博客去学,都会考虑最起码的两个问题: 我到底该咋用这种设计模式呀,直接把书上的.百度上的.博客上-的程序们抄过来? 那我该咋用呢?就算把人家程序抄过来,抄过来放在哪 ...

  10. 你以为你真的了解二进制吗?详解JDK中的二进制骚操作

    目录: [图片上传失败-(image-98c3f8-1616855044646)] 要求十进制转二进制,首先我们想到的是除2求余法,比如数字15,如下,不断的除以2,一直到0为止,最后将余数倒序排列就 ...

最新文章

  1. php常用比较函数区别表
  2. 包含Tomcat 9的JBoss Web Server 5已发布
  3. Semtech与Lacuna从太空接收信息
  4. IDEA 运行run 为灰色解决办法
  5. 嵌入式文件系统镜像制作及烧写
  6. 特征值与特征向量(二)
  7. C语言字符串库函数api
  8. asp.net中gridview 如果字数太多可以用此方法把字体变短+.....
  9. 涡轮机叶片matlab强度分析论文,一种基于MATLAB及Pro_E的涡轮建模方法
  10. bool 取反_dataframe根据bool值高效地进行多重条件筛选的
  11. Leetcode836.Rectangle Overlap矩阵重叠
  12. 20140708testC
  13. 企业如何进行客户细分 客户细分的方法和类型
  14. microsoft edge 浏览器添加兼容网址
  15. buu crypto 变异凯撒
  16. 随机抽人名小程序_篮球还可以这样玩?推荐你3个篮球趣味游戏小程序
  17. 用GRUB2来实现——坎特伯雷项目 The Canterbury Project
  18. 关于‘-[UIViewController _loadViewFromNibNamed:bundle:] loaded the “XXXView“ nib but the view outlet wa
  19. 使用C/C++来打开与关闭文件(fopenfclose)
  20. 删除文件夹及文件夹里的文件

热门文章

  1. 无穷分数java_java – 如何NaN和无穷大的浮动或双倍存储在内存?
  2. 凭实力蝉联第一!Flink 又双叒叕上榜啦
  3. Java基础---Java---正则表达式-----匹配、切割、替换、获取等方法
  4. windows安装linux无法启动服务,安装centos后无法引导启动windows7怎么办
  5. linux中安装多个mysql_Linux环境中安装多个MySQL服务笔记
  6. dede图片上传php,织梦DEDE 栏目字段添加并调用:例如图片上传
  7. ping包优化版本python
  8. python中的request库_Python中的Requests库简要总结
  9. 知识图谱构建工具_自动构建知识图谱
  10. c语言创建若干个成绩栏目,2015年计算机二级《C语言》考试上机测试题(6)