LinkedList底层运行机制
Add 添加某个节点对象
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);
分析:
-
LinkedList linkedList = new LinkedList(); public LinkedList() {}//使用无参构造器
2. 这时 linkeList 的属性 *first = null last = null* 3. 执行 添 ```java public boolean add(E e) { linkLast(e); return true; } ``` 2. 将新的结点,加入到双向链表的最后 3. 执行 添 ```java 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++; } ``` ## remove 删除某个节点对象
linkedList.remove(); // 这里默认删除的是第一个结点
linkedList.remove(2);//删除第3个元素
System.out.println("linkedList=" + linkedList);
源码分析:
linkedList.remove(); // 这里默认删除的是第一个结点
-
执行 removeFirst
public E remove() { return removeFirst(); }
-
执行public E removeFirst()
public E removeFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(f); }
-
执行 unlinkFirst, 将 f 指向的双向链表的第一个结点拿掉
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
Set 修改某个节点
linkedList.set(1, 999);
Get 得到某个结点对象
Object o = linkedList.get(1);
遍历Linkedlist 方式
迭代器遍历
**** 因为LinkedList 是 实现了List接口, 遍历方式
System.out.println("===LinkeList遍历迭代器====");
Iterator iterator = linkedList.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println("next=" + next);
增强for 遍历
for (Object o1 : linkedList) {
System.out.println("o1=" + o1);
普通for遍历
for (int i = 0; i < linkedList.size(); i++) {
System.out.println(linkedList.get(i));
}