目录
1.List常用方法
添加元素:
list.add(10);
//可以看成list.add(new Integer(10));
//自动装箱,存入集合后不分数据类型,都是对象
list={Jack,10,true};
list.addAll(Collection c);
//将c集合中的元素全部加入list集合中
list.add(index,elements);
//在index位置插入一个元素,如果不写index则默认在最后加入元素
list.add(index,Collection c);
//在index位置插入集合c的所有元素
//添加元素对另一个对象时,例
list.add(new Dog("小黑",3));
删除元素:
list.remove(0);//删除第一个元素
list.remove("0");//删除为0的元素
返回元素位置:
list.indexOf(obj);
//返回obj在集合中首次出现的位置
list.lastIndexOf(obj);
//返回obj在集合中末次出现的位置
指定位置元素替换:
list.set(index,obj);
//此index必须在集合中存在
返回fromIndex到toIndex位置子集合:
list returnList=list.subList(fromIndex,toIndex);
//前开后闭[fromIndex,toIndex),包含前面fromIndex位置的元素
2.ArrayList接口
2.1:
可以存放所有类型的元素,包括null,并且可以存放多个null。
2.2:
ArrayList的底层是由数组来实现的。
2.3:
ArrayList基本等同于Vector,但是ArrayList线程不安全(执行效率高),多线程情况下不推荐使用ArrayList,考虑用Vector。
3.LinkedList接口
3.1:
可以添加任何元素,包括null(元素可以重复)。
3.2:
LinkedList的底层是由双向链表来实现的。
LinkedList维护first(首节点)和last(尾节点)两个属性。(节点----Node对象)
底层结构示意图:
演示从头到尾遍历双向链表:
while(true){
if(first=null){
break;
}
System.out.println(first);
first=first.next;
}
3.3:
简版LinkedList增加数据源码演示及示意图:
void linkLast(E e){
final Node<E> l=last;
final Node<E> newNode=new Node<>(l,e,null);
last=newNode;
if(l=null){
first=newNode;
}else{
l.next=newNode;
}
size++;
//修改次数
modCount++;
}
4.ArrayList和LinkedList对比
ArrayList | 基于数组 | 查询快 | 存放元素都是有序可重复且能添加null;都用于单线程。 |
LinkedList | 基于链表 | 增删快 |