List除了从Collection集合继承的方法外,List 集合里添加了一些根据索引来操作集合元素的方法。
void add(int inde x, Object ele)
:在index位置插入ele元素
boolean addAll(int index, Collection eles)
:从index位置开始将eles中的元素添加进来
Object get(int index)
:获取指定index位置的元素
int indexOf(Object obj)
:返回obj在集合中首次出现的位置
int lastIndexOf(Object obj)
:返回obj在当前集合中末次出现的位置
Object remove(int index)
:移除指定index位置的元素,并返回此元素
Object set(int index, Object ele)
:设置指定index位置的元素为ele
List subList(int fromIndex, int toIndex)
:返回[fromIndex,toIndex)
处的子集合
线程不安全,效率较高。底层使用数组进行存储。进行查找、末尾添加等操作相对较多的数据通常采用ArrayList实现类。
JDK1.7(类似于单例中饿汉式)
ArrayList list = new ArrayList(); //无参构造器,底层创建了长度为10的Object[]数组elementData
list.add(123); //elementData[0] = new Integer(123);
…
list.add(11); //如果此次的添加导致底层elementData数组容量不够,则会扩容,默认情况下扩容为原来的1.5倍,同时将原有的数组中的数据复制过去
//有参构造器
ArrayList listTwo = new ArrayList(int capacity);
JDK1.8(类似于单例中懒汉式)
ArrayList list = new ArrayList(); //无参构造器,底层Object[] elementData初始化为{},即还没有创建长度为10的数组
list.add(123); //第一次调用add()时,底层才创建长度为10的数组
//其余与JDK1.7一样
注意:Arrays.asList(…)
方法返回的 List 集合,既不是 ArrayList 实例,也不是
Vector 实例。Arrays.asList(…)
返回值是一个固定长度的 List 集合。
线程不安全,效率较高。对于频繁进行插入、删除的操作,建议使用LinkedList类,效率较高。
LinkedList list = new LinkedList(); //内部声明了Node类型的first和last属性,用于记录首末元素,默认值为null
list.add(123); //创建Node对象,将123封装到Node对象中,该对象中还有prev和next两个变量,分别用来记录前一个和下一个元素的位置
Node类型的定义
private static class Node {
E item;
Node next;
Node prev;
Node(Node prev, E element, Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}