java.util.ArrayList
2016-06-03 23:27
323 查看
java.util.ArrayList
api
List 接口的大小可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。construct
ArrayList是一个顺序列表,是对一个数组的封装/** * 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 /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;
elementData数组是存储数据的容器,size表示当前存储元素的个数
ArrayList有三个构造函数
ArrayList()
默认构造函数,lazey的思想,将elementData设置为一个空数组,在
add()时初始化大小为10
ArrayList(int initialCapacity)将elementData初始化为固定指定大小
this.elementData = new Object[initialCapacity]
ArrayList(Collection<? extends E> c)
用另一个集合的底层数组来构成新的ArrayList,
elementData = c.toArray();
Collection.toArray()方法返回该集合的底层数组(ArrayList也是一个集合,实现了
interface Collection)
Collection.toArray()具体介绍
http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/Collection.html#toArray()
构造函数
ArrayList(Collection<? extends E> c)中还有一段代码,是为了处理bug 6260652
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);
因为c.toArray返回的可能不是Object[].class类型,例如返回了String[].class类型,这里用
Arrays.copyOf重新复制了一下数组,并且作了类型转化
主要方法实现
add
public boolean add(E e) { ensureCapacityInternal(size + 1);扩充容量 // Increments modCount!! elementData[size++] = e;//放入元素到数组 return true; }
get
相关文章推荐
- Java集合---ConcurrentHashMap原理分析
- 可能是屎上最容易懂的java冒泡排序
- 一个技术小白对java内存的看法~
- SpringMVC请求路径禁止自动匹配匹配".*"
- PAT L2-001紧急救援(java)
- Mac eclipse安装SVN +javaHL 安装使用详情
- 2. Spring Boot返回json数据【从零开始学Spring Boot】
- Java读取图片分辨率
- 1. spring boot起步之Hello World【从零开始学Spring Boot】
- Java类加载与反射
- Java进阶学习第二十一天——Filter学习
- (42)Spring Boot多数据源【从零开始学Spring Boot】
- java.lang.AbstractMethodError: javax.servlet.jsp.PageContext.getELContext()Ljavax/e
- java_servlet执行流程和生命周期
- MyEclipse中项目@Override注解报错问题
- Java模块 -- MyBatis 查询数据库 导出Excel文件
- JAVA之旅(十二)——Thread,run和start的特点,线程运行状态,获取线程对象和名称,多线程实例演示,使用Runnable接口
- JAVA之旅(十二)——Thread,run和start的特点,线程运行状态,获取线程对象和名称,多线程实例演示,使用Runnable接口
- Java Web开发中路径问题小结
- 【Java集合源码剖析】ArrayList源码剖析