Java: LinkedList

The LinkedList class is almost identical to the ArrayList:

import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList<String> cars = new LinkedList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars);
  }
}

// Outputs
[Volvo, BMW, Ford, Mazda]

 

ArrayList vs. LinkedList

The ArrayList class has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed.

The LinkedList stores its items in "containers." The list has a link to the first container and each container has a link to the next container in the list. To add an element to the list, the element is placed into a new container and that container is linked to one of the other containers in the list.

Use an ArrayList for storing and accessing data, and LinkedList to manipulate data.

 

LinkedList and ArrayList are two different implementations of the List interfaceLinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically re-sizing array.

 

For many cases, the ArrayList is more efficient as it is common to need access to random items in the list, but the LinkedList provides several methods to do certain operations more efficiently:

addFirst() Adds an item to the beginning of the list.
addLast() Add an item to the end of the list
removeFirst() Remove an item from the beginning of the list.
removeLast() Remove an item from the end of the list
getFirst() Get the item at the beginning of the list
getLast() Get the item at the end of the list

 

 

 

 

 

 

For LinkedList<E>

  • get(int index) is O(n) , but O(1) when index = 0 or index = list.size() - 1 (in this case, you can also use getFirst() and getLast()). 
  • add(int index, E element) is O(n), but O(1) when index = 0 or index = list.size() - 1 (in this case, you can also use addFirst() and addLast()/add()). 
  • remove(int index) is O(n), but O(1) when index = 0 or index = list.size() - 1 (in this case, you can also use removeFirst() and removeLast()).
  • Iterator.remove() is O(1)
  • ListIterator.add(E element) is O(1).

For ArrayList<E>

  • get(int index) is O(1)Main benefit of ArrayList<E>
  • add(E element) is O(1) amortized, but O(n) worst-case since the array must be resized and copied
  • add(int index, E element) is O(n) (with n/2 steps on average)
  • remove(int index) is O(n) (with n/2 steps on average)
  • Iterator.remove() is O(n) (with n/2 steps on average)
  • ListIterator.add(E element) is O(n) (with n/2 steps on average)

 

posted @ 2022-11-27 07:33  小白冲冲  阅读(36)  评论(0)    收藏  举报