dir.by  
Поиск >>

Компьютер, программы
→
Java
→
Java (class, interface, collections, etc.)
 class LinkedList in Java 
посмотрели 1372 раз
обновлено: 6 October 2026
class LinkedList<E> is a set of Nodes. Each Node has 2 links: a link to the next Node and a link to the previous Node.

LinkedList is not synchronized. If multiple threads access a LinkedList concurrently, and at least one of the threads modifies the LinkedList, then LinkedList must be synchronized.

LinkedList
  implements interface List<E> this array, i.e. you can add and remove elements, get an element by index
  implements interface Queue<E> this queue, i.e. adding, deleting elements according to the algorithm: first in - first out
  implements interface Deque<E> this is a two-way queue i.e. adding, removing elements from the beginning and end
  Java  
interface List<E> extends SequencedCollection<E>
{
Let's look at Functions >> ...
}
  Java  
interface Queue<E> extends Collection<E>
{
Let's look at Functions >> ...
}
  Java  
interface Deque<E> extends Collection<E>
{
Let's look at Functions >> ...
}
Example 1. Call the List functions
  Java     Creating a new Java console application ... and write the code
package org.example;
import java.util.LinkedList;

public class Program {
     public static void main(String[] args)
     {
          LinkedList<String> myList1 = new LinkedList<String>();

          // Add an element to the end of the queue
          myList1.add("Car");
          // myList1 = ["Car"]

          // Add an element to the end of the queue
          myList1.add("House");
          // myList1 = ["Car", "House"]

          // Add an element to the end of the queue
          myList1.add("Notebook");
          // myList1 = ["Car", "House", "Notebook"]

          // View item by index
          elem = myList1.get(1);
          // elem = "House"
          // myList1 = ["Car", "House", "Notebook"]

          // Insert element by index 1
          myList1.add(1, "Airplane");
          // myList1 = ["Car", "Airplane", "House", "Notebook"]

          // Delete item by index 1
          myList1.remove(1);
          // myList1 = ["Car", "House", "Notebook"]
     }
}
 
Example 2. Call the Queue functions
  Java     Creating a new Java console application ... and write the code
package org.example;
import java.util.LinkedList;

public class Program {
     public static void main(String[] args)
     {
          LinkedList<String> myList1 = new LinkedList<String>();

          // Add an element to the end of the queue
          myList1.offer("Car");
          // myList1 = ["Car"]

          // Add an element to the end of the queue
          myList1.offer("House");
          // myList1 = ["Car", "House"]

          // Add an element to the end of the queue
          myList1.offer("Book");
          // myList1 = ["Car", "House", "Book"]

          // View item at the top of the queue
          String elem = myList1.peek();
          // elem = "Car"
          // myList1 = ["Car", "House", "Book"]

          // Take an element from the beginning of the queue, the element is deleted
          elem = myList1.poll();
          // elem = "Car"
          // myList1 = ["House", "Book"]
     }
}
 
Example 3. Call the Deque functions
  Java     Creating a new Java console application ... and write the code
package org.example;
import java.util.LinkedList;

public class Program {
     public static void main(String[] args)
     {
          LinkedList<String> myList1 = new LinkedList<String>();

          /////// You can call the First & Last functions:
          // addFirst, addLast
          // offerFirst, offerLast
          // peekFirst, peekLasts
          // pollFirst, pollLast
          // removeFirst, removeLast

          myList1.addLast("Car");
          // myList1 = ["Car"]

          myList1.addLast("House");
          // myList1 = ["Car", "House"]

          myList1.addLast("Notebook");
          // myList1 = ["Car", "House", "Notebook"]

          myList1.addFirst("Airplane");
          // myList1 = ["Airplane", "Car", "House", "Notebook"]

          // View item at the top of the queue
          elem = myList1.peekFirst();
          // elem = "Airplane"
          // myList1 = ["Airplane", "Car", "House", "Notebook"]

          // Take an element from the beginning of the queue, the element is deleted
          elem = myList1.pollFirst();
          // elem = "Airplane"
          // myList1 = ["Car", "House", "Notebook"]

          // Take an element from the end of the queue, the element is deleted
          elem = myList1.pollLast();
          // elem = "Notebook"
          // myList1 = ["Car", "House"]
     }
}
What is the advantage of LinkedList over ArrayList:
Benefits of LinkedList:

• The main advantage of LinkedList over ArrayList is that it is more efficient to add and remove items at the beginning or middle of the list if you already have a specific Node for these operations.

• Quick insertion and deletion at the beginning of a collection: Adding or removing an element at the very beginning (addFirst(), removeFirst()) occurs in constant time O(1), while ArrayList requires shifting all subsequent memory elements O(N).

• No resizing: ArrayList stores a regular array inside it. When it is full, Java creates a new, larger array and copies the old data there — this is an expensive operation. A LinkedList is made up of individual Nodes linked by links, so it can grow indefinitely without recreating the structure.

• Implementation of the Deque interface: LinkedList implements the Deque interface (two-way queue), which allows it to be used as a full-fledged queue with offer(), poll(), and peek() methods.
When does LinkedList lose to ArrayList?

• Access by index: For ArrayList, it happens instantly O(1), and for LinkedList it is slow O(N), since you have to follow the links from the very beginning or end.

• Memory Consumption: wastes more memory, since each of its elements stores not only the value itself, but also two references (to the next and previous elements).
Documentation
  Java  
class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
     transient int size = 0;
     transient Node<E> first;
     transient Node<E> last;

     private static class Node<E> {
          E item;
          Node<E> next;
          Node<E> prev;

          Node(Node<E> prev, E element, Node<E> next) {
               this.item = element;
               this.next = next;
               this.prev = prev;
          }
     }

     public LinkedList() {
     }

     public LinkedList(Collection<? extends E> c) {
          this();
          addAll(c);
     }

     public E getFirst() {
          final Node<E> f = first;
          if (f == null)
               throw new NoSuchElementException();
          return f.item;
     }

     public E getLast() {
          final Node<E> l = last;
          if (l == null)
               throw new NoSuchElementException();
          return l.item;
     }

     public E removeFirst() {
          final Node<E> f = first;
          if (f == null)
               throw new NoSuchElementException();
          return unlinkFirst(f);
     }

     public E removeLast() {
          final Node<E> l = last;
          if (l == null)
               throw new NoSuchElementException();
          return unlinkLast(l);
     }

     public void addFirst(E e) {
          linkFirst(e);
     }

     public void addLast(E e) {
          linkLast(e);
     }

     public boolean contains(Object o) {
          return indexOf(o) >= 0;
     }

     public int size() {
          return size;
     }

     public boolean add(E e) {
          linkLast(e);
          return true;
     }

     public boolean remove(Object o) {
          if (o == null) {
               for (Node<E> x = first; x != null; x = x.next) {
                    if (x.item == null) {
                         unlink(x);
                         return true;
                    }
               }
          } else {
               for (Node<E> x = first; x != null; x = x.next) {
                    if (o.equals(x.item)) {
                         unlink(x);
                         return true;
                    }
               }
          }
          return false;
     }

     public boolean addAll(Collection<? extends E> c) {
          return addAll(size, c);
     }

     public boolean addAll(int index, Collection<? extends E> c) {
          checkPositionIndex(index);

          Object[] a = c.toArray();
          int numNew = a.length;
          if (numNew == 0)
               return false;

          Node<E> pred, succ;
          if (index == size) {
               succ = null;
               pred = last;
          } else {
               succ = node(index);
               pred = succ.prev;
          }

          for (Object o : a) {
               @SuppressWarnings("unchecked") E e = (E) o;
               Node<E> newNode = new Node<>(pred, e, null);
               if (pred == null)
                    first = newNode;
               else
                    pred.next = newNode;
               pred = newNode;
          }

          if (succ == null) {
               last = pred;
          } else {
               pred.next = succ;
               succ.prev = pred;
          }

          size += numNew;
          modCount++;
          return true;
     }

     public void clear() {
          // Clearing all of the links between nodes is "unnecessary", but:
          // - helps a generational GC if the discarded nodes inhabit
          // more than one generation
          // - is sure to free memory even if there is a reachable Iterator
          for (Node<E> x = first; x != null; ) {
               Node<E> next = x.next;
               x.item = null;
               x.next = null;
               x.prev = null;
               x = next;
          }
          first = last = null;
          size = 0;
          modCount++;
     }

     public E get(int index) {
          checkElementIndex(index);
          return node(index).item;
     }

     public E set(int index, E element) {
          checkElementIndex(index);
          Node<E> x = node(index);
          E oldVal = x.item;
          x.item = element;
          return oldVal;
     }

     public void add(int index, E element) {
          checkPositionIndex(index);

          if (index == size)
               linkLast(element);
          else
               linkBefore(element, node(index));
     }

     public E remove(int index) {
          checkElementIndex(index);
          return unlink(node(index));
     }

     // Search Operations
     public int indexOf(Object o) {
          int index = 0;
          if (o == null) {
               for (Node<E> x = first; x != null; x = x.next) {
                    if (x.item == null)
                         return index;
                    index++;
               }
          } else {
               for (Node<E> x = first; x != null; x = x.next) {
                    if (o.equals(x.item))
                         return index;
                    index++;
               }
          }
          return -1;
     }

     public int lastIndexOf(Object o) {
          int index = size;
          if (o == null) {
               for (Node<E> x = last; x != null; x = x.prev) {
                    index--;
                    if (x.item == null)
                         return index;
               }
          } else {
               for (Node<E> x = last; x != null; x = x.prev) {
                    index--;
                    if (o.equals(x.item))
                         return index;
               }
          }
          return -1;
     }

     // Queue operations.
     public E peek() {
          final Node<E> f = first;
          return (f == null) ? null : f.item;
     }

     public E element() {
          return getFirst();
     }

     public E poll() {
          final Node<E> f = first;
          return (f == null) ? null : unlinkFirst(f);
     }

     public E remove() {
          return removeFirst();
     }

     public boolean offer(E e) {
          return add(e);
     }

     public boolean offerFirst(E e) {
          addFirst(e);
          return true;
     }

     public boolean offerLast(E e) {
          addLast(e);
          return true;
     }

     public E peekFirst() {
          final Node<E> f = first;
          return (f == null) ? null : f.item;
     }

     public E peekLast() {
          final Node<E> l = last;
          return (l == null) ? null : l.item;
     }

     public E pollFirst() {
          final Node<E> f = first;
          return (f == null) ? null : unlinkFirst(f);
     }

     public E pollLast() {
          final Node<E> l = last;
          return (l == null) ? null : unlinkLast(l);
     }

     public void push(E e) {
          addFirst(e);
     }

     public E pop() {
          return removeFirst();
     }

     public boolean removeFirstOccurrence(Object o) {
          return remove(o);
     }

     public boolean removeLastOccurrence(Object o) {
          if (o == null) {
               for (Node<E> x = last; x != null; x = x.prev) {
                    if (x.item == null) {
                         unlink(x);
                         return true;
                    }
               }
          } else {
               for (Node<E> x = last; x != null; x = x.prev) {
                    if (o.equals(x.item)) {
                         unlink(x);
                         return true;
                    }
               }
          }
          return false;
     }

     public ListIterator<E> listIterator(int index) {
          checkPositionIndex(index);
          return new ListItr(index);
     }

     public Object clone() {
          LinkedList<E> clone = superClone();

          // Put clone into "virgin" state
          clone.first = clone.last = null;
          clone.size = 0;
          clone.modCount = 0;

          // Initialize clone with our elements
          for (Node<E> x = first; x != null; x = x.next)
               clone.add(x.item);

          return clone;
     }

     public Object[] toArray() {
          Object[] result = new Object[size];
          int i = 0;
          for (Node<E> x = first; x != null; x = x.next)
               result[i++] = x.item;
          return result;
     }

     public <T> T[] toArray(T[] a) {
          if (a.length < size)
               a = (T[])java.lang.reflect.Array.newInstance(
                         a.getClass().getComponentType(), size);
          int i = 0;
          Object[] result = a;
          for (Node<E> x = first; x != null; x = x.next)
               result[i++] = x.item;

          if (a.length > size)
               a[size] = null;

          return a;
     }

     public Spliterator<E> spliterator() {
          return new LLSpliterator<>(this, -1, 0);
     }

     public LinkedList<E> reversed() {
          return new ReverseOrderLinkedListView<>(this, super.reversed(), Deque.super.reversed());
     }
}
Learn more about methods in the Java documentation:https://docs.oracle.com ...
 
← Previous topic
interface Deque<E> in Java
 
Next topic →
interface Set in Java
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
Download and install
• Installation JDK (download and install the Java library for Windows)
• Download and install IntelliJ IDEA to explore Java, Spring, Jakarta EE | Functionality and differences: Community | Ultimate
• Error "JDK is missing" | Java
Java (class, interface, collections, etc.)
• Create a simple console app in IntelliJ IDEA to learn Java
• Access modifiers (private, protected, public) for a class and for methods and fields. | Java
• Collections in Java
• interface List<E> in Java
• class ArrayList<E> in Java
• class Vector<E> in Java
• class Stack<E> in Java
• class CopyOnWriteArrayList<E> in Java
• interface Queue<E> in Java
• interface Deque<E> in Java
• class LinkedList<E> in Java
• interface Set in Java
• class HashSet<E> in Java
• class LinkedHashSet<E> in Java
• Collections.singletonList("Hello") returns an immutable list containing exactly one specified element | Java collection
• class Collections (all functions, algorithms) | Java
• stream.filter(...) select elements according to your criterion | Java collection | Example: allCars.stream().filter(item -> item.Price < 30000).toList()
• What is interface in Java ?
• Directly in the code (at runtime) we make an implementation for the interface | Java
• Threads in Java
• lambda is an unnamed method (no name and no class owned) | Java
• Exceptions and handling in Java. Example: try {...} catch (Exception e) {...}
• Why use throws Exception in the function name in Java? Answer: The method throws an exception and there is no handling of try catch. Example: float CalculateDensity(float mass, float volume) throws Exception { ... throw new Exception("Error! Volume is zero."); ... }
Java web application (servlet, jsp page, basic functionality and no frameworks)
• Creating a new simple web application (jsp web page) | Java, Maven
• Create a web servlet (the servlet is located on the web server, returns the result on request) | Java
• Installation Tomcat web server (download and install for Windows)
• Check, test Tomcat web server (create a new my.hml file)
• What is Maven
• What is a dynamic web page jsp (Java Server Page) ?
• How to install Smart Tomcat plugin in Intellij Idea
• Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java
Spring in Java (Spring Framework, Spring Data, Spring Boot, ...)
• What is Spring? Why use Spring in Java?
• What is Spring Bean? What is Spring Container? IoC (inversion of control) | Creating a simple Spring project and configuration Spring Container in an XML file | Editor IntelliJ Idea and language Java
• What is Dependency Injection in Spring? Creating a simple Spring project with Dependency Injection in the constructor with the attributes @Component, @Autowired | Editor IntelliJ Idea and language Java
• Create a new Spring Web application (the request goes to the Controller → Controller creates a response as text or json) | Java, Spring Web, Spring Boot, Maven
• Creating a new Spring WebSocket application (Java WebSocket sends a message to the JavaScript WebSocket) | Java, Spring WebSocket, Spring Boot, Maven
• Create Azure Web App with the type Java (free). That is, create an empty web server
• Put the Java Spring web application in Azure
• Connect to the application Azure Web App (Java) via FTP | use File Explorer
• Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java, Spring Boot
• How to install Spring WebSocket plugin in Intellij Idea
Jakarta EE / Java EE in Java (Web Applications, Web Services)
• What is Jakarta EE (Java EE)? | In which editor (program) is it convenient to write Jakarta EE (Java EE) code?
• Creating a simple web project in IntelliJ Idea Ultimate | Jakarta EE (Java EE)
Struts in Java (extends API Java Servlet using MVC)
• What is Struts | Java
Courses, training
• Course "Java developer" from Yandex
Interview
• Interviews on Java

  Ваши вопросы присылайте по почте: info@dir.by