各自努力,最高处见!加油!
集合(二)
一、ArrayList类
1.ArrayList的注意事项
- permits all elements,including null,ArrayList可以加入null,并且可以加入多个。
- ArrayList是由数组来实现数据存储的。
- ArrayList基本等同于Vector,除了ArrayList是线程不安全(执行效率高)。在多线程情况下不建议使用ArrayList。
2.ArrayList的底层操作机制源码分析(重点难点)底层源码分析:韩顺平老师30天入门java 510课
- ArrayList中维护了一个Object类型的数组elementData。
transient Object[ ] elsmentData;
//transient表示瞬间,短暂的,表示该属性不会被序列化。 - 当创建ArrayList对象时,如果使用的是无参构造器,则初始的elementData容量为0.第一次添加,则扩容elementData为10,如需再次扩容,则扩容elementData为1.5倍。
- 如果使用的是指定大小的构造器,则初始elementData容量为指定大小,如果需要扩容,则直接扩容为1.5倍。
二、Vector类说明
- Vector底层也是一个对象数组,
protected Object[ ] elementData;
- Vector底层是线程同步的,即线程安全。(Vector类的操作方法都有synchronize)
- 在开发中,需要线程同步安全时,考虑使用Vector。
三、Vector底层结构和ArrayList的比较
四、LinkedList类
1、双向链表复习
import org.w3c.dom.Node;
/**
* 双向链表复习
* */
public class LinkedList01 {
public static void main(String[] args) {
Node1 jack = new Node1(new String("jack"));
Node1 tom=new Node1(new String("tom"));
Node1 xmt=new Node1(new String("xmt"));
jack.next=tom;
tom.next=xmt;
xmt.pre=tom;
tom.pre=jack;
Node1 first=jack;
Node1 last=xmt;
//正向遍历链表
while (true){
if (first==null){
break;
}
System.out.println(first);
first=first.next;
}
//插入元素(可以设置一个插入的方法)
Node1 happy=new Node1(new String("happy"));
happy.next=xmt;
happy.pre=tom;
tom.next=happy;
xmt.pre=happy;
System.out.println("==反向遍历==");
//反向遍历
first=jack;//复原头结点
while (true){
if(last==null){
break;
}
System.out.println(last);
last=last.pre;
}
}
}
class Node1{
public Object item;
public Node1 next;
public Node1 pre;
public Node1(Object item) {
this.item = item;
}
@Override
public String toString() {
return "Node1{" +
"item=" + item +
'}';
}
}
2、LinkedList底层结构
import java.util.Iterator;
import java.util.LinkedList;
public class LInkedListCRUD {
public static void main(String[] args) {
LinkedList linkedList=new LinkedList();
//添加节点
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
System.out.println(linkedList);
//删除节点
linkedList.remove();
System.out.println(linkedList);
//修改节点
linkedList.set(1,789);
System.out.println(linkedList);
//得到某个对象
System.out.println(linkedList.get(1));
//遍历:1.迭代器 2.增强for循环
Iterator iterator=linkedList.iterator();
System.out.println("==遍历链表==");
//1.迭代器
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//2.增强for循环
for (Object o :linkedList) {
System.out.println(o);
}
}
}
删除节点原理
五、ArrayList和LinkedList的比较
数组:增加删除慢,查找(修改)快。
链表:增加删除快,查找(修改)慢。
如何选择ArrayList和LinkedList:
- 改查多,用ArrayList(一般程序都是查询较多,所以ArrayList使用频率高)
- 增删多,LinkedList
- 两者都是线程不安全的,都要在单线程情况下使用。