ArrayList容量
import java.lang.reflect.Field;
import java.util.ArrayList;
/**
* Class Name test02
* Author F4367281
* Date 2020/4/18 9:41
* Version 1.0
**/
public class test02 {
public static int getCapacity(ArrayList arrayList){
try{
Field field = ArrayList.class.getDeclaredField("elementData");
field.setAccessible(true);
return ((Object[]) field.get(arrayList)).length;
}catch (Exception e){
e.printStackTrace();
}
return -1;
}
public static void main(String[] args){
ArrayList<String> arrayList = new ArrayList<String>();
System.out.println("capacity: "+getCapacity(arrayList) + ", size: "+arrayList.size());
arrayList.add("testdfadsf");
System.out.println("capacity: "+getCapacity(arrayList) + ", size: "+arrayList.size());
arrayList = new ArrayList<String>(20);
System.out.println("capacity: "+getCapacity(arrayList) + ", size: "+arrayList.size());
}
}
默认容量是10,其实ArrayList源码里面有写。
ArrayList,LinkedList,Vector的区别
1.ArrayList,Vector是数组方式存储数据,插入数据慢,涉及到数组元素移动内存操作。查找数据通过下标,所以查询数据快。
2.Vector因为使用了synchronized修饰,线程安全,但性能比AarrayList差。
3.LinkedList使用双向链表实现存储,按序号索引数据,需要向前或向后遍历,查找比较慢;但插入数据只需记录前后节点信息即可,插入数据快。链表中index是标记元素相对于链表头部的node个数,在根据index查询时,可以结合index和链表的size的关系提高查询性能。当index大致在链表前半部分时(index<(size>>1)),从链表头部开始遍历更快;反之,在后半部分时(index>(size>>1)),从后面开始遍历更快。