摘要: Java知识点总结(Java容器-LinkedList) LinkedList 底层实现是双向循环链表,所以增删元素效率高,查询慢。线程安全 ArrayList和LinkedList比较 ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构 对于水机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList要移动指针 对于新增和删除操作add和remove,LinkedList比较占优势,因为ArrayList要移动数据 这一点要看实际情况的。
Java知识点总结(Java容器-LinkedList)
LinkedList
底层实现是双向循环链表,所以增删元素效率高,查询慢。线程安全
ArrayList和LinkedList比较
- ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构
- 对于水机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList要移动指针
- 对于新增和删除操作add和remove,LinkedList比较占优势,因为ArrayList要移动数据
这一点要看实际情况的。若只对单条数据插入或删除,ArrayList的速度反而优于LinkedList。但若是批量随机的插入删除数据,LinkedList的速度大大优于ArrayList. 因为ArrayList每插入一条数据,要移动插入点及之后的所有数据。
手写LinkedList
public class MyLinkedList /*implements List<E>*/ {
private Node first;
private Node last;
private int size ;
//新增元素
public void add(Object obj) {
if (first == null) {
Node n = new Node(null,obj,null);
first = n;
last = n;
}else {
//直接往last后增加新的节点
Node n = new Node(last, obj, null);
last.setNext(n);
last = n;
}
size++;
}
//获取元素
public Object get(int index) throws Exception {
return getNode(index).getObj();
}
//删除元素
public boolean remove(int index) throws Exception {
boolean flag = false;
Node temp = getNode(index);
if (temp!=null) {
temp.getPreview().setNext(temp.getNext());
temp.getNext().setPreview(temp.getPreview());
size--;