创建对象:与其他普通的引用数据类型创建方式完全相同,但要指定容器中存储的数据类型:

ArrayList<要存储元素的数据类型> 变量名 = new ArrayList<要存储元素的数据类型>();

集合中存储的元素,只能为<>括号中指定的数据类型元素;
“<要存储元素的数据类型>”中的数据类型必须是引用数据类型,不能是基本数据类型;
下面给出8种基本数据类型所对应的引用数据类型表示形式:

基本数据类型 对应的引用数据类型表示形式
byte Byte
short Short
Int Integer
long Long
float Float
double Double
char Character
boolean Boolean

附上java基本类型

常用方法
方法声明 功能描述
boolean add(Object obj) 将指定元素obj追加到集合的末尾
Object get(int index) 返回集合中指定位置上的元素
int size() 返回集合中的元素个数
boolean add(int index, Object obj) 将指定元素obj插入到集合中指定的位置
Object remove(int index) 从集合中删除指定index处的元素,返回该元素
void clear() 清空集合中所有元素
Object set(int index, Object obj) 用指定元素obj替代集合中指定位置上的元素

ArrayList源码解析

package java.util;public class ArrayList<E> extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{// 序列版本号private static final long serialVersionUID = 8683452581122892189L;// 默认容量大小private static final int DEFAULT_CAPACITY = 10;// 空数组private static final Object[] EMPTY_ELEMENTDATA = {};// 用于保存ArrayList中数据的数组private transient Object[] elementData;// ArrayList中所包含元素的个数private int size;// 带初始容量参数的构造函数public ArrayList(int initialCapacity) {super();if (initialCapacity < 0)throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);this.elementData = new Object[initialCapacity];}// 默认构造函数,其默认初始容量为10public ArrayList() {super();this.elementData = EMPTY_ELEMENTDATA;}// 带Collection参数的构造函数public ArrayList(Collection<? extends E> c) {elementData = c.toArray();size = elementData.length;// c.toArray might (incorrectly) not return Object[] (see 6260652)if (elementData.getClass() != Object[].class)elementData = Arrays.copyOf(elementData, size, Object[].class);}// 将此 ArrayList 实例的容量调整为列表的当前大小(实际元素个数)public void trimToSize() {modCount++;if (size < elementData.length) {elementData = Arrays.copyOf(elementData, size);}}// 如有必要,增加此 ArrayList 实例的容量,以确保它至少能够容纳最小容量参数所// 指定的元素数public void ensureCapacity(int minCapacity) {int minExpand = (elementData != EMPTY_ELEMENTDATA)// any size if real element table? 0// larger than default for empty table. It's already supposed to be// at default size.: DEFAULT_CAPACITY;if (minCapacity > minExpand) {ensureExplicitCapacity(minCapacity);}}private void ensureCapacityInternal(int minCapacity) {if (elementData == EMPTY_ELEMENTDATA) {minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);}ensureExplicitCapacity(minCapacity);}private void ensureExplicitCapacity(int minCapacity) {modCount++;// overflow-conscious codeif (minCapacity - elementData.length > 0)grow(minCapacity);}private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;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);}private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}// 返回ArrayList中的元素个数public int size() {return size;}// 判断ArrayList是否为空public boolean isEmpty() {return size == 0;}// 判断ArrayList是否包含Object(o)public boolean contains(Object o) {return indexOf(o) >= 0;}// 返回ArrayList中首次出现的指定元素的索引,或如果此列表不包含元素,则返回 -1public 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;}// 返回ArrayList中最后一次出现的指定元素的索引,或如果此列表不包含索引,则返回 -1public 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;}// 返回此 ArrayList 实例的浅表副本public Object clone() {try {@SuppressWarnings("unchecked")ArrayList<E> v = (ArrayList<E>) super.clone();// 将当前ArrayList的全部元素拷贝到v中v.elementData = Arrays.copyOf(elementData, size);v.modCount = 0;return v;} catch (CloneNotSupportedException e) {// this shouldn't happen, since we are Cloneablethrow new InternalError();}}// 按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组public Object[] toArray() {return Arrays.copyOf(elementData, size);}// 返回ArrayList的模板数组。所谓模板数组,即可以将T设为任意的数据类型@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;}// 位置访问操作   @SuppressWarnings("unchecked")E elementData(int index) {return (E) elementData[index];}// 返回ArrayList中指定位置上的元素public E get(int index) {rangeCheck(index);return elementData(index);}// 用指定的元素替代ArrayList中指定位置上的元素,并返回替代前的元素public E set(int index, E element) {rangeCheck(index);E oldValue = elementData(index);elementData[index] = element;return oldValue;}// 将指定的元素添加到ArrayList的尾部public boolean add(E e) {ensureCapacityInternal(size + 1);  // Increments modCount!!elementData[size++] = e;return true;}// 将指定的元素插入ArrayList中的指定位置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++;}// 移除ArrayList中指定位置上的元素,并返回该位置上的元素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;}// 移除ArrayList中首次出现的指定元素(如果存在则移除并返回true,否则返回false)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;}// 私有方法,用于快速移除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}// 移除ArrayList中的所有元素public void clear() {modCount++;// clear to let GC do its workfor (int i = 0; i < size; i++)elementData[i] = null;size = 0;}// 按照指定 collection 的迭代器所返回的元素顺序,// 将该 collection 中的所有元素添加到ArrayList的尾部public boolean addAll(Collection<? extends E> c) {Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew);  // Increments modCountSystem.arraycopy(a, 0, elementData, size, numNew);size += numNew;return numNew != 0;}// 从指定的位置开始,将指定 collection 中的所有元素插入到ArrayList中public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew);  // Increments modCountint numMoved = size - index;if (numMoved > 0)System.arraycopy(elementData, index, elementData, index + numNew,numMoved);System.arraycopy(a, 0, elementData, index, numNew);size += numNew;return numNew != 0;}// 移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素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 workint newSize = size - (toIndex-fromIndex);for (int i = newSize; i < size; i++) {elementData[i] = null;}size = newSize;}// 私有方法,用于范围检测private void rangeCheck(int index) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}// 私有方法,用于add和addAllprivate void rangeCheckForAdd(int index) {if (index > size || index < 0)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}private String outOfBoundsMsg(int index) {return "Index: "+index+", Size: "+size;}// 移除ArrayList中Collection所包含的所有元素public boolean removeAll(Collection<?> c) {return batchRemove(c, false);}// 保留所有ArrayList和Collection共有的元素public boolean retainAll(Collection<?> c) {return batchRemove(c, true);}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 workfor (int i = w; i < size; i++)elementData[i] = null;modCount += size - w;size = w;modified = true;}}return modified;}// java.io.Serializable的写入函数// 将ArrayList的“容量,所有的元素值”都写入到输出流中private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{// Write out element count, and any hidden stuffint expectedModCount = modCount;s.defaultWriteObject();// Write out size as capacity for behavioural compatibility with clone()s.writeInt(size);// Write out all elements in the proper order.for (int i=0; i<size; i++) {s.writeObject(elementData[i]);}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}}// java.io.Serializable的读取函数:根据写入方式读出// 先将ArrayList的“容量”读出,然后将“所有的元素值”读出private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {elementData = EMPTY_ELEMENTDATA;// Read in size, and any hidden stuffs.defaultReadObject();// Read in capacitys.readInt(); // ignoredif (size > 0) {// be like clone(), allocate array based upon size not capacityensureCapacityInternal(size);Object[] a = elementData;// Read in all elements in the proper order.for (int i=0; i<size; i++) {a[i] = s.readObject();}}}// 返回一个从指定位置开始遍历的ListIterator迭代器public ListIterator<E> listIterator(int index) {if (index < 0 || index > size)throw new IndexOutOfBoundsException("Index: "+index);return new ListItr(index);}// 返回一个ListIterator迭代器public ListIterator<E> listIterator() {return new ListItr(0);}// 返回一个Iterator迭代器public Iterator<E> iterator() {return new Itr();}// 返回一个指定范围的子List列表public List<E> subList(int fromIndex, int toIndex) {subListRangeCheck(fromIndex, toIndex, size);return new SubList(this, 0, fromIndex, toIndex);}
}

Java ArrayList集合常用方法相关推荐

  1. 杨老师课堂之ArrayList集合常用方法解析

    ArrayList集合常用方法的解析 1.概述 ​ 在前面我们学习了数组,数组可以保存多个元素,但在某些情况下无法确定到底要保存多少个元素,此时数组将不再适用,因为数组的长度不可变.例如,要保存一个学 ...

  2. java ArrayList集合

    ArrayList集合是程序中最常见的一种集合,它属于引用数据类型(类).在ArrayList内部封装了一个长度可变的数组,当存入的元素超过数组长度时,ArrayList会在内存中分配一个更大的数组来 ...

  3. java ArrayList集合概述和基本使用 基础

    数组与ArrayList的区别:  1.数组的长度不可以发生改变  2.ArrayList集合的长度是可以随意发生变化 常用 ArrayList()           构造一个初始容量为 10 的空 ...

  4. [Java基础]ArrayList集合常用方法

  5. (day5) 自学Java——ArrayList集合

    目录 1. ArrayList 2.集合练习 (1)添加字符串和整数,并遍历 (2)添加学生对象并遍历 (3)查找用户是否存在 (4)返回多个数据 1. ArrayList 数组有个致命的弱点,那就是 ...

  6. (Java)ArrayList集合

    ArrayList集合概述和基本使用 ArrayList是可以动态增长和缩减的索引序列,它是基于数组实现的List类. 数组的长度不可以发生改变,但是ArrayList的长度是可以随时变化的 对于Ar ...

  7. Java学习之路-day-09 ArrayList集合

    Java ArrayList集合 每日一句 1. ArrayList 1.1 ArrayList类概述 1.2 ArrayList类常用方法 1.3 ArrayList存储字符串并遍历 1.4 Arr ...

  8. java arraylist 方法返回值_返回arraylist方法

    ArrayList 什么是ArrayList 可以简单的认为是一个动态数组:实际上ArrayList就是用数组实现的,长度不够时,调用Arrays.copyOf方法,拷贝当前数组到一个新的长度更大的数 ...

  9. 【零基础学Java】—ArrayList集合概述和基本使用(十四)

    [零基础学Java]-ArrayList集合概述和基本使用(十四) 一.什么是ArrayList类以及注意事项 java.util.ArrayList是大小可变的数组的实现,存储在内的数据称为元素,此 ...

最新文章

  1. 卷积神经网络精确率不增反降_深度学习 第四门课:卷积神经网络(Convolutional Neural Networks)...
  2. dagger2的初次使用
  3. linux kernel 调度,在Linux中,实时调度_kernel_开发99编程知识库
  4. linux glibc安装mysql_Linux安装MySQL-5.6.24-1.linux_glibc2.5.x86_64.rpm
  5. DockOne微信分享(一一零):Docker在沪江落地的实践
  6. 读《我是一只IT小小鸟》有感
  7. Unity NavMesh寻路 A*(A star)分析及实例应用(一)
  8. 【历史上的今天】7 月 4 日:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生
  9. Flask入门---@app.route()使用
  10. ARD智能电动机控制器在苯乙烯生产过程中的应用
  11. BERT源码深度剖析之create_pretraining_data.py
  12. Apple Watch 关闭显示正在听的音乐
  13. 学习笔记 查分约束系统
  14. idea中重写接口中方法没有自动生产@Override怎么办?
  15. ssd(Single Shot MultiBox Detector)代码之(五) 训练自己的数据集
  16. ie8兼容性问题(五) event对象、e.target和e.preventDefault
  17. R语言学习:卡方检验
  18. 倒计时制作代码(计时器)
  19. 认知心理学有感(2)-感觉与知觉
  20. 获取微信公众号信息接口

热门文章

  1. 常用KINDLE书籍下载网址
  2. AV1解码器dav1d用meson生成visual studio2017工程
  3. 树莓派raspberry bullseye扩大虚拟内存
  4. 讲师加油站 | 003 | 关于讲师PPT课件的7条忠告
  5. 产品经理如何做好项目管理
  6. 打印机php源码分析,PHP版本的网络打印机提交打印代码
  7. 4月16日 第二次站立会议-------疯狂猜成语 参会人员:杨霏,袁雪,胡潇丹,郭林林,尹亚男,赵静娜...
  8. php fread指针,PHP中的fread()函数
  9. Linux IPC shm
  10. JUST技术:分布式一致性协议概念及Raft协议简介