În acest tutorial, vom afla despre Java LinkedList în detaliu cu ajutorul exemplelor.
LinkedList
Clasa cadrului colecțiilor Java oferă funcționalitatea structurii lista de date legate ( de două ori LinkedList).

Fiecare element dintr-o listă legată este cunoscut sub numele de nod . Se compune din 3 câmpuri:
- Prev - stochează o adresă a elementului anterior în listă. Este
null
pentru primul element - Următorul - stochează o adresă a următorului element din listă. Este
null
pentru ultimul element - Date - stochează datele reale
Crearea unei Java LinkedList
Iată cum putem crea liste legate în Java:
LinkedList linkedList = new LinkedList();
Aici, Type indică tipul unei liste conectate. De exemplu,
// create Integer type linked list LinkedList linkedList = new LinkedList(); // create String type linked list LinkedList linkedList = new LinkedList();
Exemplu: Creați LinkedList în Java
import java.util.LinkedList; class Main ( public static void main(String() args)( // create linkedlist LinkedList animals = new LinkedList(); // Add elements to LinkedList animals.add("Dog"); animals.add("Cat"); animals.add("Cow"); System.out.println("LinkedList: " + animals); ) )
Ieșire
LinkedList: (câine, pisică, vacă)
În exemplul de mai sus, am creat LinkedList
animale numite.
Aici, am folosit add()
metoda pentru a adăuga elemente la LinkedList. Vom afla mai multe despre add()
metodă mai târziu în acest tutorial.
Lucrarea unei Java LinkedList
Elementele din listele legate nu sunt stocate în ordine. În schimb, acestea sunt împrăștiate și conectate prin legături ( Prev și Next ).

Aici avem 3 elemente într-o listă legată.
- Dog - este primul element care deține nul ca adresa anterioară și adresa lui Cat ca adresa următoare
- Pisica - este al doilea element care deține o adresă a câinelui ca adresă anterioară și adresa vacii ca adresă următoare
- Vaca - este ultimul element care deține adresa lui Cat ca adresă anterioară și nulă ca element următor
Pentru a afla mai multe, vizitați Structura de date LinkedList.
Metode de Java LinkedList
LinkedList
oferă diverse metode care ne permit să efectuăm operațiuni diferite în liste legate. Vom analiza patru operatori LinkedList frecvent utilizați în acest tutorial:
- Adăugați elemente
- Elemente de acces
- Schimbați elementele
- Eliminați elementele
1. Adăugați elemente într-o LinkedList
Putem folosi add()
metoda pentru a adăuga un element (nod) la sfârșitul LinkedList. De exemplu,
import java.util.LinkedList; class Main ( public static void main(String() args)( // create linkedlist LinkedList animals = new LinkedList(); // add() method without the index parameter animals.add("Dog"); animals.add("Cat"); animals.add("Cow"); System.out.println("LinkedList: " + animals); // add() method with the index parameter animals.add(1, "Horse"); System.out.println("Updated LinkedList: " + animals); ) )
Ieșire
LinkedList: (câine, pisică, vacă) Actualizat LinkedList: (câine, cal, pisică, vacă)
În exemplul de mai sus, am creat o LinkedList numită animale. Aici am folosit add()
metoda pentru a adăuga elemente animalelor.
Observați declarația,
animals.add(1, "Horse");
Aici am folosit parametrul numărului de index . Este un parametru opțional care specifică poziția în care este adăugat noul element.
Pentru a afla mai multe despre adăugarea de elemente la LinkedList, accesați programul Java pentru a adăuga elemente la LinkedList.
2. Accesați elementele LinkedList
get()
Metoda clasei LinkedList este folosită pentru a avea acces la un element din LinkedList. De exemplu,
import java.util.LinkedList; class Main ( public static void main(String() args) ( LinkedList languages = new LinkedList(); // add elements in the linked list languages.add("Python"); languages.add("Java"); languages.add("JavaScript"); System.out.println("LinkedList: " + languages); // get the element from the linked list String str = languages.get(1); System.out.print("Element at index 1: " + str); ) )
Ieșire
LinkedList: (Python, Java, JavaScript) Element la indexul 1: Java
In the above example, we have used the get()
method with parameter 1. Here, the method returns the element at index 1.
We can also access elements of the LinkedList using the iterator()
and the listIterator()
method. To learn more, visit the Java program to access elements of LinkedList.
3. Change Elements of a LinkedList
The set()
method of LinkedList
class is used to change elements of the LinkedList. For example,
import java.util.LinkedList; class Main ( public static void main(String() args) ( LinkedList languages = new LinkedList(); // add elements in the linked list languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); languages.add("Java"); System.out.println("LinkedList: " + languages); // change elements at index 3 languages.set(3, "Kotlin"); System.out.println("Updated LinkedList: " + languages); ) )
Output
LinkedList: (Java, Python, JavaScript, Java) Updated LinkedList: (Java, Python, JavaScript, Kotlin)
In the above example, we have created a LinkedList named languages. Notice the line,
languages.set(3, "Kotlin");
Here, the set()
method changes the element at index 3 to Kotlin.
4. Remove element from a LinkedList
The remove()
method of the LinkedList
class is used to remove an element from the LinkedList. For example,
import java.util.LinkedList; class Main ( public static void main(String() args) ( LinkedList languages = new LinkedList(); // add elements in LinkedList languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); languages.add("Kotlin"); System.out.println("LinkedList: " + languages); // remove elements from index 1 String str = languages.remove(1); System.out.println("Removed Element: " + str); System.out.println("Updated LinkedList: " + languages); ) )
Output
LinkedList: (Java, Python, JavaScript, Kotlin) Removed Element: Python New LinkedList: (Java, JavaScript, Kotlin)
Here, the remove()
method takes the index number as the parameter. And, removes the element specified by the index number.
To learn more about removing elements from the linkedlist, visit the Java program to remove elements from LinkedList…
Other Methods
Methods | Description |
---|---|
contains() | checks if the LinkedList contains the element |
indexOf() | returns the index of the first occurrence of the element |
lastIndexOf() | returns the index of the last occurrence of the element |
clear() | removes all the elements of the LinkedList |
iterator() | returns an iterator to iterate over LinkedList |
LinkedList as Deque and Queue
Since the LinkedList
class also implements the Queue and the Deque interface, it can implement methods of these interfaces as well. Here are some of the commonly used methods:
Methods | Descriptions |
---|---|
addFirst() | adds the specified element at the beginning of the linked list |
addLast() | adds the specified element at the end of the linked list |
getFirst() | returns the first element |
getLast() | returns the last element |
removeFirst() | removes the first element |
removeLast() | removes the last element |
peek() | returns the first element (head) of the linked list |
poll() | returns and removes the first element from the linked list |
offer() | adds the specified element at the end of the linked list |
Example: Java LinkedList as Queue
import java.util.LinkedList; import java.util.Queue; class Main ( public static void main(String() args) ( Queue languages = new LinkedList(); // add elements languages.add("Python"); languages.add("Java"); languages.add("C"); System.out.println("LinkedList: " + languages); // access the first element String str1 = languages.peek(); System.out.println("Accessed Element: " + str1); // access and remove the first element String str2 = languages.poll(); System.out.println("Removed Element: " + str2); System.out.println("LinkedList after poll(): " + languages); // add element at the end languages.offer("Swift"); System.out.println("LinkedList after offer(): " + languages); ) )
Output
LinkedList: (Python, Java, C) Accessed Element: Python Removed Element: Python LinkedList after poll(): (Java, C) LinkedList after offer(): (Java, C, Swift)
Example: LinkedList as Deque
import java.util.LinkedList; import java.util.Deque; class Main ( public static void main(String() args)( Deque animals = new LinkedList(); // add element at the beginning animals.add("Cow"); System.out.println("LinkedList: " + animals); animals.addFirst("Dog"); System.out.println("LinkedList after addFirst(): " + animals); // add elements at the end animals.addLast("Zebra"); System.out.println("LinkedList after addLast(): " + animals); // remove the first element animals.removeFirst(); System.out.println("LinkedList after removeFirst(): " + animals); // remove the last element animals.removeLast(); System.out.println("LinkedList after removeLast(): " + animals); ) )
Output
LinkedList: (Cow) LinkedList after addFirst(): (Dog, Cow) LinkedList after addLast(): (Dog, Cow, Zebra) LinkedList after removeFirst(): (Cow, Zebra) LinkedList after removeLast(): (Cow)
Iterating through LinkedList
We can use the Java for-each loop to iterate through LinkedList. For example,
import java.util.LinkedList; class Main ( public static void main(String() args) ( // Creating a linked list LinkedList animals = new LinkedList(); animals.add("Cow"); animals.add("Cat"); animals.add("Dog"); System.out.println("LinkedList: " + animals); // Using forEach loop System.out.println("Accessing linked list elements:"); for(String animal: animals) ( System.out.print(animal); System.out.print(", "); ) ) )
Output
LinkedList: (Cow, Cat, Dog) Accessing linked list elements: Cow, Cat, Dog,
LinkedList Vs. ArrayList
Both the Java ArrayList and LinkedList
implements the List
interface of the Collections
framework. However, there exists some difference between them.
LinkedList | ArrayList |
---|---|
Implements List , Queue , and Deque interfaces. | Implements List interface. |
Stores 3 values (previous address, data, and next address) in a single position. | Stochează o singură valoare într-o singură poziție. |
Oferă implementarea listei dublu legată. | Oferă o implementare matricială redimensionabilă. |
Ori de câte ori este adăugat un element prev și next adresa sunt schimbate. | Ori de câte ori se adaugă un element, toate elementele după poziția respectivă sunt deplasate. |
Pentru a accesa un element, trebuie să iterăm de la început la element. | Poate accesa aleatoriu elemente folosind indexuri. |
Notă : Putem crea și o LinkedList folosind interfețe în Java. De exemplu,
// create linkedlist using List List animals1 = new LinkedList(); // creating linkedlist using Queue Queue animals2 = new LinkedList(); // creating linkedlist using Deque Deque animals3 = new LinkedList();
Aici, dacă LinkedList este creat folosind o singură interfață, atunci nu putem folosi metode furnizate de alte interfețe. Adică, animalele1 nu pot folosi metode specifice Queue
și Deque
interfețe.