java 容器 结论+源码分析 总结 (1)_WXTS的博客-CSDN博客
内容随时更新,最大程度的分析每个方法
依旧接着讨论List集合
List
2、ArrayList
ArrayList是一个动态数组,说明它的低层数据结构也是一个数组,Vector也是一个动态数组,而ArrayList和Vector不同之处在于,Vector是一个线程同步的,而ArrayList不是线程同步的
基本用法:类似于数组
@Test
public void arrayListTest1() {
//创建一个ArrayList对象
ArrayList<Object> objects = new ArrayList<Object>();
//往ArrayList对象中添加1~10数据
for (int i = 0; i < 10; i++) {
objects.add(i + 1);
}
//1、取出数据
for (int i = 0; i < 10; i++) {
System.out.print(objects.get(i)+" ");
}
System.out.println();
//2、也可以调用toArray方法,返回一个数组,拿到储存的数据
Object[] objects1 = objects.toArray();
//2.1 打印取出的数据
for (Object o : objects1) {
System.out.print(o+" ");
}
}
构造方法:
通过查看源码可知,创建一个ArrayList集合,有3种方法
1、空参和构造方法 pulic ArrrayList()
2、传入一个初始化大小的构造方法public ArrayList(int iniialCapacity)
3、传入一个Collection集合的构造方法public ArrayList(Collectiion<? extends E> c)
方法源码:
boolean | add(E e) 向列表的尾部添加指定的元素(可选操作)。 |
void | add(int index, E element) 在列表的指定位置插入指定元素(可选操作)。 |
boolean | addAll(Collection<? extends E> c) 添加指定 collection 中的所有元素到此列表的结尾,顺序是指定 collection 的迭代器返回这些元素的顺序(可选操作)。 |
boolean | addAll(int index, Collection<? extends E> c) 将指定 collection 中的所有元素都插入到列表中的指定位置(可选操作)。 |
boolean add(E e)源码进行
跟进源码,查看elementData,size
/**
* 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
//查看源码可知这个是ArrayList用来储存数据的数组缓冲区(The array buffer into which the elements of the ArrayList are stored),且
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;//可知是一个列表储存的元素个数
跟进源码private void add()
跟进源码grow()
跟进源码newCapacity()
哪进源码hugeCapacity()
结论:ArrayLIst的add方法和Vector的add方法几乎差不多,用法一样,而且底层设计也差不多,都是基于动态数组,只不过在扩容的时候,扩容的大小方式不一样而已。