In this article, we are going to go through everything you need to know to use Java LinkedList appropriately and what happens behind the curtains when we use it. We will cover both its practical and theoretical use.
1. What is a LinkedList?
In Java, a LinkedList
is a doubly linked list, and it is a list of objects linked together via reference. Each item in a LinkedList
is a Node and each Node holds the actual item and two other Nodes, or references if you will, one pointing to the previous item (unless this one is the first Node, the HEAD, then it should be null), and the other one pointing to the next item (unless this one is the last Node, the TAIL, then it should be null).
Here is a diagram of a LinkedList
.
1.1 Java LinkedList Hierarchy
The Java LinkedList
hierarchy is better explained with the help of a diagram.
The diagram above shows the abstract class the LinkedList
extends and all interfaces it implements.
1.2 Java LinkedList Characteristics
- It is a doubly linked list.
- It may contain duplicates and null values.
- Critical sections are not synchronized, consequently not thread safe.
- Insertion ordem is kept.
- It implements fail-fast for both
iterator
andlistIterator
.
1.3 Time Complexity with Big-O Notation
A good understanding of the time complexity in the LinkedList
will help us decide which list implementation is most suitable for our business logic.
Due to Java optimization, some methods such as add(index), set(index, object), get(index), and remove(index) are, in reality, O(n/2)
— Bear in mind this is not Big-O notation, regardless of whether it would traverse half of the list or the whole list, it would still be O(n), but it is good to know we are getting a little increase in performance. Whenever an operation uses an index, it will check whether this index is in the first or second half of the LinkedList
using the Signed Right Shift Operator and, if it is the first, it will traverse the list from its head, otherwise from its tail.
Whenever using add(index, object), Java will check whether the index is equal to size and, if it is, this will be a O(1) operation.
2. Java LinkedList Initialization
The LinkedList
class offers only two constructors for initialization, an empty one and one that takes a Collection.
2.1 Initializing an Empty LinkedList
Let’s instantiate a LinkedList
of Integers and add five elements to it then print it. Note that you can only use classes to specify its type. Primitives won’t work!
private static void newingALinkedList() { LinkedList<Integer> linkedList = new LinkedList<>(); linkedList.add(1); linkedList.add(2); linkedList.add(3); linkedList.add(4); linkedList.add(5); System.out.println(linkedList); }
Output:
[1, 2, 3, 4, 5]
2.2 Initializing a LinkedList Passing a Collection
What actually happens here is that this constructor will invoke the empty one by calling this()
and then it will invoke the addAll(Collection c)
method passing the collection. The order of the LinkedList
created is the same returned by the collection’s iterator. For this example, we will create a method that returns a HashSet of integers and pass it as a parameter to our constructor.
private static Set<Integer> getSetCollection() { return new HashSet<>() {{ add(1); add(5); add(3); add(2); add(4); }}; }
Initializing our LinkedList
from a collection.
private static void newingALinkedListPassingACollection() { LinkedList<Integer> linkedList = new LinkedList<>(getSetCollection()); System.out.println(linkedList); }
Output:
[1, 2, 3, 4, 5]
2.3 Initializing a LinkedList for Concurrent Environment
As stated by the Java documentation, the LinkedList
class does not have its critical sections synchronized and should your application have any thread that modifies the list structurally, it must be synchronized externally. If your LinkedList
is encapsulated inside an object and all the critical section is synchronized, perfect, if it isn’t, then it should be wrapped using Collections.synchronizedList method. Here is an example:
private static void newingALinkedListForConcurrentEnvironment() { List<Integer> list = Collections.synchronizedList(new LinkedList<>(Arrays.asList(1,2,3,4,5))); System.out.println(list); }
We won’t dive into multithreading here. If you want to learn more about that check out our article on multithreading.
Output:
[1, 2, 3, 4, 5]
3. Java LinkedList Methods
In this section, we will go through all methods provided by the LinkedList
API.
3.1 Java LinkedList Adding Methods
The LinkedList
class offers ten different adding methods to choose from. Keep in mind that any adding method that takes an integer as the index parameter will throw an IndexOutOfBoundsException
if the index is less than zero or greater than the LinkedList
size.
3.1.1 boolean add(E e)
Adds an element at the end (tail) of the LinkedList
. If it is the first insertion or there is only one element, it will also point to the head of the list, that is, invoking any method to retrieve the first or the last element will return the same item.
- Parameter: e — an element of type E. It must match the
LinkedList
type. - Returns:
true
.
private static void add() { LinkedList<String> words = new LinkedList<>(); words.add("Code"); words.add("Learn"); words.add("Hub"); System.out.println(words); }
Output:
[Code, Learn, Hub]
3.1.2 void addLast(E e)
It works just like the previous method, except it returns void
. Internally, both invoke the same void linkLast(E e)
method.
- Parameter: e — an element of type E. It must match the
LinkedList
type.
private static void addLast() { LinkedList<String> words = new LinkedList<>(); words.addLast("Code"); words.addLast("Learn"); words.addLast("Hub"); System.out.println(words); }
Output:
[Code, Learn, Hub]
3.1.3 void addFirst(E e)
Adds an element to the beginning (head) of the LinkedList
.
Note that we have inverted the order of the elements, so now we first added the literal “Hub”, then we added “Learn” before “Hub“, and finally we added “Code” before “Learn”.
- Parameter: e — an element of type E. It must match the
LinkedList
type.
private static void addFirst() { LinkedList<String> words = new LinkedList<>(); words.addFirst("Hub"); words.addFirst("Learn"); words.addFirst("Code"); System.out.println(words); }
Output:
[Code, Learn, Hub]
3.1.4 void push(E e)
It is the same as invoking void addFirst(E e)
and it will produce the same result. Under the hood, the addFirst
method will be called.
- Parameter: e — an element of type E. It must match the
LinkedList
type.
private static void push() { LinkedList<String> words = new LinkedList<>(); words.push("Hub"); words.push("Learn"); words.push("Code"); System.out.println(words); }
Output:
[Code, Learn, Hub]
3.1.5 void add(int index, E element)
Adds an element at the specified position (index).
- Parameter: index — the index (position) of type
int
to be added. - Parameter: element — an element of type E. It must match the
LinkedList
type. - Throws:
IndexOutOfBoundsException
.
private static void addAtIndex() { LinkedList<String> words = new LinkedList<>(); words.add(0, "Hub"); words.add(0, "Learn"); words.add(0, "Code"); System.out.println(words); }
Output:
[Code, Learn, Hub]
3.1.6 boolean addAll(int index, Collection<? extends E> c)
Adds all elements of a collection to the end of a LinkedList
. The order of the elements
depends on the Collection
‘s iterator.
- Parameter: index — the index (position) of type
int
from where insertion will begin. - Parameter: c —
Collection
from which elements will be added at the end of theLinkedList
. - Returns:
true
if the operation is successful. For aLinkedList
, it can only returnfalse
if theCollection
is empty, that is, no element has been appended. - Throws:
IndexOutOfBoundsException
.
We will create a method that returns a LinkedList
and pass it as a parameter to the method.
private static LinkedList<String> getWords() { return new LinkedList<>(){{ add("Code"); add("Learn"); add("Hub"); add("Helps"); add("You"); add("Learn"); add("Java"); }}; }
Let’s also create a print(List<?> list
) method to print out our LinkedList
in a more elegant way.
private static void print(boolean before, List<?> list) { System.out.print(before ? "Before: " : "After: "); for (int i = 0; i < list.size(); i++) { if (i == list.size() - 1) { System.out.println(list.get(i) + "!"); return; } System.out.print(list.get(i) + " "); } }
Now the actual method that will invoke the add all method.
private static void addAllStartingAtIndex() { LinkedList<String> words = new LinkedList<>(); words.add("Hey,"); print(true, words); words.addAll(words.size(), getWords()); print(false, words); }
To make things more interesting, firstly we added an element to our LinkedList
, then we invoked the addAll
method passing our LinkedList
size()
method as a parameter and our getWords()
method which will return an LinkedList
.
Output:
Before: Hey,! After: Hey, Code Learn Hub Helps You Learn Java!
3.1.7 boolean addAll(Collection<? extends E> c)
It invokes the previous method, addAll(int index, Collection<? extends E> c)
, passing size
for the index parameter.
- Parameter: c —
Collection
from which elements will be added at the end of theLinkedList
. - Returns:
true
if the operation is successful. For aLinkedList
, it can only returnfalse
if theCollection
is empty, that is, no element has been appended.
This method is nearly identical to the previous one.
3.1.8 boolean offer(E e)
Invokes boolean add(E e) internally.
- Parameter: e — an element of type E. It must match the
LinkedList
type. - Returns:
true
.
private static void offer() { LinkedList<String> words = getWords(); print(true, words); words.offer("... Awesome"); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Learn Hub Helps You Learn Java ... Awesome!
3.1.9 boolean offerFirst(E e)
Invokes void addFirst(E e)
internally.
- Parameter: e — an element of type E. It must match the
LinkedList
type. - Return:
true
.
private static void offerFirst() { LinkedList<String> words = getWords(); print(true, words); words.offerFirst("Hey, "); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Hey, Code Learn Hub Helps You Learn Java!
3.1.10 boolean offerLast(E e)
Invokes void addLast(E e)
internally.
- Parameter: e — an element of type E. It must match the
LinkedList
type. - Return:
true
.
private static void offerLast() { LinkedList<String> words = getWords(); print(true, words); words.offerLast("... Awesome"); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Learn Hub Helps You Learn Java ... Awesome!
3.2 Java LinkedList Removing Methods
The LinkedList
class offers eight different removing methods to choose from. Keep in mind that any removing method that takes an integer as the index parameter will throw an IndexOutOfBoundsException
if the index is less than zero or greater than or equal to the LinkedList
size, that is, if your LinkedLIst
is empty, an exception will be thrown.
3.2.1 E remove()
Removes and returns the first element (head) from the LinkedList
. It’s the same as invoking removeFirst()
.
- Returns: the element of type E in the head of the
LinkedList
. - Throws:
NoSuchElementException
if theLinkedList
is empty.
private static void remove() { LinkedList<String> words = getWords(); print(true, words); words.remove(); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Learn Hub Helps You Learn Java!
3.2.2 E removeFirst()
This method is identical to remove()
. As mentioned before, internally, remove()
invokes removeFirst()
.
- Returns: the element of type E in the head of the
LinkedList
. - Throws:
NoSuchElementException
if theLinkedList
is empty.
3.2.3 E removeLast()
Removes and returns the last element (tail) from the LinkedList
.
- Return:s the element of type E in the head of the
LinkedList
. - Throws:
NoSuchElementException
if theLinkedList
is empty.
private static void removeLast() { LinkedList<String> words = getWords(); print(true, words); words.removeLast(); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Learn Hub Helps You Learn!
3.2.4 boolean remove(Object o)
Removes the first occurrence of the specified element passed as a parameter from the LinkedList if the element is present.
- Parameter: o — the element to be removed from the
LinkedList
. - Returns:
true
if theLinkedList
contained the specified element.
private static void removeElement() { LinkedList<String> words = getWords(); print(true, words); words.remove("You"); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Learn Hub Helps Learn Java!
Note that the word “You” is no longer there.
3.2.5 E remove(int index)
Removes and returns the element at the specified index (position) in this LinkedList
.
- Parameter: index — the index of the element to remove from the
LinkedList
. - Returns:
true
if theLinkedList
contained the specified element. - Throws:
IndexOutOfBoundsException
.
private static void removeAtIndex() { LinkedList<String> words = getWords(); print(true, words); words.remove(4); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Learn Hub Helps Learn Java!
3.2.6 boolean removeFirstOccurrence(Object o)
Removes the first occurrence of the specified element in the LinkedList
traversing from head to tail. Does nothing if element is not in the list. It is the same as invoking boolean remove(Object o)
, that is exactly what this method does internally.
- Parameter: o — the element to remove from the
LinkedList
. - Returns:
true
if theLinkedList
contained the specified element.
private static void removeFirstOccurrence() { LinkedList<String> words = getWords(); print(true, words); words.removeFirstOccurrence("Learn"); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Hub Helps You Learn Java!
3.2.7 boolean removeLastOccurrence(Object o)
Removes the last occurrence of the specified element in the LinkedList
traversing from tail to head. Does nothing if element is not in the list.
- Parameter: o — the element to remove from the
LinkedList
. - Returns:
true
if theLinkedList
contained the specified element.
private static void removeLastOccurrence() { LinkedList<String> words = getWords(); print(true, words); words.removeLastOccurrence("Learn"); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Learn Hub Helps You Java!
3.2.8 E pop()
Just like E remove()
method, it invokes E removeFirst()
internally.
- Returns: the element of type E in the head of the
LinkedList
. - Throws:
NoSuchElementException
if theLinkedList
is empty.
private static void pop() { LinkedList<String> words = getWords(); print(true, words); words.pop(); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Learn Hub Helps You Learn Java!
3.3 Java LinkedList Retrieving Methods
The LinkedList
class offers ten methods for retrieving elements to choose from. Some of them will remove the element from the list, others won’t. Keep in mind that any retrieving method that takes an integer as the index parameter will throw an IndexOutOfBoundsException
if the index is less than zero or greater than or equal to the LinkedList
size, that is, if your list is empty, an exception will be thrown.
3.3.1 E get(int index)
Retrieves the element at the specified index (position) in the LinkedList
. It will NOT remove the element.
- Parameter: index — the index (position) of type
int
of the element to be returned. - Returns: the element at the specified index (position) in the
LinkedList
. - Throws:
IndexOutOfBoundsException
.
private static void getAtIndex() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.get(6)); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Java After: Code Learn Hub Helps You Learn Java!
3.3.2 E getFirst()
Retrieves the first element in the LinkedList
. It will NOT remove the element.
- Returns: the element of type
E
in the head of theLinkedList
. - Throws:
NoSuchElementException
if theLinkedList
is empty.
private static void getFirst() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.getFirst()); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Code After: Code Learn Hub Helps You Learn Java!
3.3.3 E getLast()
Retrieves the last element in the LinkedList
. It will NOT remove the element.
- Returns: the element of type
E
in the tail of theLinkedList
. - Throws:
NoSuchElementException
if theLinkedList
is empty.
private static void getLast() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.getLast()); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Java After: Code Learn Hub Helps You Learn Java!
3.3.4 E element()
Invokes E getFirst()
internally.
- Returns: the element of type
E
in the head of theLinkedList
. - Throws:
NoSuchElementException
if theLinkedList
is empty.
private static void element() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.element()); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Code After: Code Learn Hub Helps You Learn Java!
3.3.5 E peek()
Retrieves the first element (head) of the LinkedList. Returns null
if LinkedList
is empty. It will NOT remove the element.
- Returns: the element of type
E
in the head of theLinkedList
.
private static void peek() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.peek()); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Code After: Code Learn Hub Helps You Learn Java!
3.3.6 E peekFirst()
It behaves exactly the same as the previous method E peek()
.
- Returns: the element of type
E
in the head of theLinkedList
.
private static void peekFirst() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.peekFirst()); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Code After: Code Learn Hub Helps You Learn Java!
3.6.7 E peekLast()
Returns the last element (tail) of the LinkedList or null
if LinkedList
is empty. It will NOT remove the element.
- Returns: the element of type
E
in the tail of theLinkedList
.
private static void peekLast() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.peekLast()); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Java After: Code Learn Hub Helps You Learn Java!
3.6.8 E poll()
Retrieves and removes the head (first element) of the LinkedList
. Returns null
if LinkedList
is empty. This method works just like E remove()
, except it doesn’t throw an Exception
. Actually, they both invoke the same private method internally.
- Returns: the element of type
E
in the head of theLinkedList
.
private static void poll() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.poll()); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Code After: Learn Hub Helps You Learn Java!
3.6.9 E pollFirst()
Retrieves and removes the head (first element) of the LinkedList
. Returns null
if LinkedList
is empty. Same as invoking E poll()
.
- Returns: the element of type
E
in the head of theLinkedList
.
private static void pollFirst() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.pollFirst()); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Code After: Learn Hub Helps You Learn Java!
3.6.10 E pollLast()
Retrieves and removes the tail (last element) of the LinkedList
. Returns null
if LinkedList
is empty. This method works just like E removeLast()
, except it doesn’t throw an Exception
. Actually, they both invoke the same private method internally.
- Returns: the element of type
E
in the head of theLinkedList
.
private static void pollLast() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Element retrieved: " + words.pollLast()); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Element retrieved: Java After: Code Learn Hub Helps You Learn!
3.4 Java LinkedList Useful Methods
The LinkedList
class offers some useful methods for retrieving the element’s index, checking whether an element exists in the LinkedList
, getting its size or for clearing it. We will go through every one of them.
3.4.1 boolean contains(Object o)
Returns true if and only if the LinkedList
contains at least one element e
equals to o
, passed as parameter in the method. Internally it executes indexOf(o) >= 0
, that is, if it has an index, it exists in the list.
- Parameter:
o
— element whose presence in the LinkedList is to be checked. - Returns:
true
if element is in theLinkedList
, otherwisefalse
.
We will check and print two elements, one of which is contained within the LinkedList
and the other, null
, which isn’t. We won’t be printing the LinkedList twice since there’ll be modifications.
private static void contains() { LinkedList<String> words = getWords(); print(true, words); System.out.println("Contains element: " + words.contains("Learn")); System.out.println("Contains element: " + words.contains(null)); }
Output:
Before: Code Learn Hub Helps You Learn Java! Contains element: true Contains element: false
3.4.2 int indexOf(Object o)
Returns the index of the first occurrence of the specified element in the LinkedList
, or -1 if there is no such index.
- Parameter:
o
— the element to look for in the LinkedList. - Returns: the index of the first occurrence of the element, if found, or -1 if not.
private static void indexOf() { LinkedList<String> words = getWords(); print(true, words); int index = words.indexOf("You"); System.out.println("The index of \"" + words.get(index) + "\" is: " + index); }
Output:
Before: Code Learn Hub Helps You Learn Java! The index of "You" is: 4
3.4.3 int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element in the LinkedList
, or -1 if there is no such index. This method will traverse the LinkedList
from tail to head.
- Parameter:
o
— the element to look for in the LinkedList. - Returns: the index of the last occurrence of the element, if found, or -1 if not.
private static void lastIndexOf() { LinkedList<String> words = getWords(); print(true, words); int index = words.indexOf("Learn"); int lastIndex = words.lastIndexOf("Learn"); System.out.println("The FIRST index of \"" + words.get(index) + "\" is: " + index); System.out.println("The LAST index of \"" + words.get(lastIndex) + "\" is: " + lastIndex); }
Output:
Before: Code Learn Hub Helps You Learn Java! The FIRST index of "Learn" is: 1 The LAST index of "Learn" is: 5
3.4.4 int size()
Returns the number of elements in the LinkedList
.
- Returns: the number of elements in the
LinkedList
.
private static void size() { LinkedList<String> words = getWords(); print(true, words); System.out.println("LinkedList size is: " + words.size()); words.remove(4); print(false, words); System.out.println("LinkedList size is: " + words.size()); }
Output:
Before: Code Learn Hub Helps You Learn Java! LinkedList size is: 7 After: Code Learn Hub Helps Learn Java! LinkedList size is: 6
3.4.5 void clear()
Removes all elements from the LinkedList
and it will be empty afterwards.
private static void clear() { LinkedList<String> words = getWords(); print(true, words); words.clear(); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After:
As you can see, the LinkedList
is empty.
3.5 Java LinkedList Copying Methods
The LinkedList class offers three methods for copying its elements. We will go through each one of them.
3.5.1 Object clone()
Creates a shallow copy (one that does not copy the values, instead it copies the references) of this LinkedList
. The elements themselves are not cloned. — states the documentation. However, if you are working with String
objects (because of the way Java handles strings in memory), it will work as if it were a deep copy.
- Returns: a shallow copy of this
LinkedList
instance.
private static void shallowClone() { LinkedList<AtomicInteger> numbers = new LinkedList<>(); numbers.add(new AtomicInteger(0)); numbers.add(new AtomicInteger(10)); // Unchecked cast LinkedList<AtomicInteger> cloned = (LinkedList<AtomicInteger>)numbers.clone(); numbers.add(new AtomicInteger(100)); numbers.removeFirst(); System.out.println("Element changed in numbers: " + numbers.peek().incrementAndGet()); System.out.println("Element changed in numbers: " + numbers.peekLast().incrementAndGet()); System.out.println("Numbers " + numbers); System.out.println("Cloned " + cloned); }
Output:
Element changed in numbers: 11 Element changed in numbers: 101 Numbers [11, 101] Cloned [0, 11]
As you can see, changes made to the first LinkedList
, numbers, reflected on the cloned one, ergo, it is a shallow copy. Bear in mind that additions and deletions won’t have any effects in any other collection other than the one you are adding to or deleting from, as demonstrated by the output:
Number ten was incremented, and it reflected on the cloned list, then the addition followed by incrementation only affected numbers as well as the deletion of the number zero which remained in the cloned list.
One more thing to keep in mind is that the two lists point to different addresses, so they are not the same. Nonetheless, the mutable objects contained within them, for instance the atomic integer whose initial value was ten, do point to the same object in memory, that is, the one in the original LinkedList
and the one in cloned LinkedList
point to the address in memory. Let’s try using String
values.
private static void deepClone() { LinkedList<String> words = getWords(); System.out.println("Original:"); print(true, words); LinkedList<String> cloned = (LinkedList<String>)words.clone(); System.out.println("Cloned:"); print(true, cloned); words.addFirst("Indeed,"); words.set(7, "Programming"); words.remove(5); System.out.println("Original:"); print(false, words); System.out.println("Cloned:"); print(false, cloned); }
Output:
Original: Before: Code Learn Hub Helps You Learn Java! Cloned: Before: Code Learn Hub Helps You Learn Java! Original: After: Indeed, Code Learn Hub Helps Learn Programming! Cloned: After: Code Learn Hub Helps You Learn Java!
As you can see, the cloned LinkedList is exactly the same as it was when we cloned.
We have created a diagram to show graphically what shallow copy and deep copy look like.
3.5.2 Object[] toArray()
Creates and returns an array containing all the elements in the LinkedList
in proper sequence (from first to last element).
- Returns: an array containing all the elements in the
LinkedList
in proper sequence.
First, let’s create an overloaded version of our print
method which, instead of taking a List as its second parameter will take an array.
private static void print(boolean before, Object[] array) { print(before, Arrays.stream(array).toList()); }
Instead of using String, we will be using a user-defined class, ProgrammingLanguage, just so we can show some things you should be aware of.
public class ProgrammingLanguage { private String language; public ProgrammingLanguage(String language) { this.language = language; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } @Override public String toString() { return getLanguage(); } }
Now, let’s add a method to return a LinkedList of language objects so we can have some data to work with.
private static LinkedList<ProgrammingLanguage> getLanguages() { return new LinkedList<>() {{ add(new ProgrammingLanguage("Java")); add(new ProgrammingLanguage("C#")); add(new ProgrammingLanguage("Swift")); add(new ProgrammingLanguage("C++")); }}; }
Let’s write the actual code to copy our LinkedList
into a new array.
private static void toArray() { LinkedList<ProgrammingLanguage> languages = getLanguages(); System.out.println("Original:"); print(true, languages); Object[] cloned = languages.toArray(); System.out.println("Cloned:"); print(true, cloned); languages.addFirst(new ProgrammingLanguage("JavaScript")); languages.get(4).setLanguage("PHP"); languages.remove(3); System.out.println("Original:"); print(false, languages); System.out.println("Cloned:"); print(false, cloned); }
Output:
Original: Before: Java C# Swift C++! Cloned: Before: Java C# Swift C++! Original: After: JavaScript Java C# PHP! Cloned: After: Java C# Swift PHP!
As you can see, the LinkedList
and the array are identical before any modification. Any addition or deletions will have no effects on each other. However, any modification to items will reflect on both as demonstrated by the change of the language C++ into PHP.
The returned array will be of type Object and casting will either result in compile time error or runtime error.
//Compile time error //String[] noWay = languages.toArray(); //Runtime error //String[] tryMe = (String[]) languages.toArray(); //You should use the overloaded method instead.
3.5.3 <T> T[] toArray(T[] a)
Returns an array of the specified type passed containing all the elements in this list in proper sequence (from first to last element) and, if the list does NOT fit in the specified array, a new array with the runtime type of the specified array and the size of this list will be created, otherwise, all elements will be added to the array passed as a parameter.
- Parameter: a — the array into which the elements of the list will be copied to.
- Returns: an array containing all the elements in the
LinkedList
in proper sequence. - Throws:
ArrayStoreException
if the runtime type of the array passed is not a supertype of the runtime type of every element in theLinkedList
. - Throws:
NullPointerException
if the array passed isnull
.
private static void toTypedArray() { LinkedList<ProgrammingLanguage> languages = getLanguages(); System.out.println("Original:"); print(true, languages); ProgrammingLanguage[] tenLanguages = { new ProgrammingLanguage("Python"), new ProgrammingLanguage("Java"), new ProgrammingLanguage("JavaScript"), new ProgrammingLanguage("C#"), new ProgrammingLanguage("PHP"), new ProgrammingLanguage("C/C++"), new ProgrammingLanguage("R"), new ProgrammingLanguage("TypeScript"), new ProgrammingLanguage("Swift"), new ProgrammingLanguage("Objective-C") }; ProgrammingLanguage[] cloned = languages.toArray(tenLanguages); System.out.println("Cloned:"); print(true, cloned); cloned[1].setLanguage("Ruby"); languages.get(2).setLanguage("Kotlin"); languages.add(new ProgrammingLanguage("Python")); languages.add(new ProgrammingLanguage("Objective-C")); System.out.println("Original:"); print(false, languages); System.out.println("Cloned:"); print(false, cloned); }
First, we initialized our list of languages normally, then we created an array of ProgrammingLanguages
and named it tenLanguages
, next we cloned our LinkedList
passing the tenLanguages
array (what happens here is that this array will be used to store all the data coming from the list, then it will check if the array is bigger than the list, which it is, so it will set the next available placeholder to null
, which can be seen when we printed cloned list, right after the C++ language), finally it returns the array.
Output:
Original: Before: Java C# Swift C++! Cloned: Before: Java C# Swift C++ null C/C++ R TypeScript Swift Objective-C! Original: After: Java Ruby Kotlin C++ Python Objective-C! Cloned: After: Java Ruby Kotlin C++ null C/C++ R TypeScript Swift Objective-C!
3.5.3.1 Copying Issues
One important thing to note is that any elements in the array passed as parameter will be overridden by the ones in the LinkedList; that happens because the array will always start adding at index zero and if the array is bigger than the list, a null
element will be added to the next placeholder, finally, if the array passed contains elements whose indexes are higher than the list size, those elements will be kept in the array, if that is not what you want, you should clear the array first.
Some considerations:
- The returned array still holds the elements after the
null
element. - The change made on the second element of the array “Ruby” reflected on LinkedList.
- The change made on the
LinkedList
“Kotlin” reflected on the array. - Additions and deletions do not have any effects on either the array or the
LinkedList
. - It is a shallow copy.
3.6 Java LinkedList Modifying Methods
LinkedList itself offers just one method for modifying its content. Later we will check some of the inherited methods that can also perform some of the operations we have been doing so far. They are not defined nor are they overridden in the LinkedList
, instead they are inherited from abstract classes and interfaces (when they offer a default implementation.
For example, the ArrayList
in Java overrides the replaceAll
method from List, the LinkedList
doesn’t.
3.6.1 E set(int index, E element)
Replaces the element at the specified index (position) in the LinkedList
with the element passed as parameter.
- Parameter: index — the index (position) of the element to replace.
- Parameter: element — the element to be stored at the specified index.
- Returns: the element that has just been replaced, that is, the old element.
- Throws:
IndexOutOfBoundsException
.
private static void set() { LinkedList<String> words = getWords(); print(true, words); words.set(6, "any Language"); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Learn Hub Helps You Learn any Language!
3.7 Iterator Methods of Java LinkedList
An Iterator
is an object that can be used to loop through collections and its name, iterator
, comes from iterating which is a technical term for looping. It takes the place of Enumeration
in the Java Collections Framework. Iterators differ from enumerations in two ways:
- Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
- They have improved (better) method names.
3.7.1 ListIterator<E> listIterator(int index)
An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list. A ListIterator
has no current element, and its cursor position always lies between the elements returned by previous()
and or next()
. An iterator for a list of length n
has n + 1
possible cursor positions, as illustrated by the image below:
- Parameter: index — the index of the first element to return from the list-iterator by calling
next()
. - Returns: a
ListIterator
over theLinkedList
. - Throws:
IndexOutOfBoundsException
.
First let’s create a method to print our list-Iterator, so we won’t have to code it every time we print it. Our method checks whether you want to print it ascending or descending.
private static void printIterator(ListIterator<String> listIterator, boolean ascending) { if (ascending) { System.out.println("Ascending Iterator:"); while (listIterator.hasNext()) { System.out.println(listIterator.next()); } } else { System.out.println("Descending Iterator:"); while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); } } System.out.println(); }
Now the list-iterator method.
private static void listIterator() { LinkedList<String> words = getWords(); print(true, words); ListIterator<String> listIterator = words.listIterator(0); printIterator(listIterator, true); printIterator(listIterator, false); listIterator = words.listIterator(4); printIterator(listIterator, true); }
Output:
Before: Code Learn Hub Helps You Learn Java! Ascending Iterator: Code Learn Hub Helps You Learn Java Descending Iterator: Java Learn You Helps Hub Learn Code Ascending Iterator: You Learn Java
As you can see, our first list-iterator started from the beginning, the second from the end in descending order and the last at index four. Keep in mind you can also invoke listIterator()
passing no arguments, from the AbstractList
which internally will return listIterator(0)
.
3.7.1.1 List-Iterator Fail-Fast
The iterator()
and listIterator()
methods are fail-fast, which means any structural modification to the LinkedList after the creation of the iterator will result in Exception
, except modifications through the list-iterator methods add and remove.
private static void failFast() { LinkedList<String> words = getWords(); print(true, words); ListIterator<String> listIterator = words.listIterator(0); /* THIS WILL RESULT IN EXCEPTION UNCOMMENT TO GIVE IT A TRY */ // words.add("Hey,"); /* THIS WILL ALSO RESULT IN EXCEPTION UNCOMMENT TO GIVE IT A TRY */ // words.remove(); /* THIS IS PERFECTLY FINE */ words.set(words.size() - 1, "any Language"); printIterator(listIterator, true); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Ascending Iterator: Code Learn Hub Helps You Learn any Language After: Code Learn Hub Helps You Learn any Language!
3.7.1.2 boolean hasNext();
- Returns: Returns
true
if the list-iterator has more elements when traversing forwardly.
3.7.1.3 E next()
- Returns: the next element in the
LinkedList
and moves the cursor one position forwardly. - Throws:
NoSuchElementException
— if the iteration has no next element.
3.7.1.4 boolean hasPrevious()
- Returns: Returns
true
if the list-iterator has more elements when traversing backwardly.
3.7.1.5 E previous()
- Returns: the next element in the
LinkedList
and moves the cursor one position backwardly. - Throws:
NoSuchElementException
— if the iteration has no next element.
3.7.1.6 int nextIndex()
- Returns: the index of the element that it would be returned by a subsequent call to next, or the list size if the list iterator is at the end of the list.
3.7.1.7 int previousIndex()
- Returns: the index of the element that would be returned by a subsequent call to previous, or -1 if the list iterator is at the beginning of the list.
3.7.1.8 void remove()
Removes from the LinkedList
the last element returned by next or previous. We can only invoke this method after calling next()
or previous()
and only if the add()
method hasn’t been called after either one.
- Returns: Removes the last element from the
LinkedList
returned by next or previous. - Throws:
UnsupportedOperationException
— if the list iterator does not support the remove operation. - Throws:
IllegalStateException
— if invokes before callingnext()
norprevious()
or after the last call tonext()
orprevious()
, that is, the cursor value is either -1 or the list size.
private static void listIteratorRemove() { LinkedList<String> words = getWords(); print(true, words); ListIterator<String> listIterator = words.listIterator(0); while (listIterator.hasNext()) { /* Calling remove() will result in Exception. */ //listIterator.remove(); // UNCOMMENT FOR A RUNTIME EXCEPTION System.out.println(listIterator.next()); /* CALLING ADD RIGHT BEFORE REMOVE WILL THROW AN EXCEPTION */ //listIterator.add("FAIL"); // UNCOMMENTING THIS WILL CAUSE AN EXCEPTION listIterator.remove(); // THIS WORKS FINE IF ADD IS COMMENTED OUT! //listIterator.remove(); // CALL TWICE IN A ROW AND YOUR CODE BLOWS } print(false, words); // EMPTY LINKED LIST BY NOW }
Output:
Before: Code Learn Hub Helps You Learn Java! Code Learn Hub Helps You Learn Java After:
3.7.1.9 void add(E e)
Inserts the specified element into the list. The element is inserted immediately before the next element and after previous, and, if the LinkedList
is empty, the element is inserted before the cursor and the only way to retrieve it is by invoking previous()
, calling next()
after the insertion of an element in an empty LinkedList
or at the end of it will result in Exception.
- Parameter: e — the element to add.
- Throws:
UnsupportedOperationException
if the list iterator does not support the remove operation. - Throws:
ClassCastException
if the class of the specified element prevents the addition to this list. - Throws:
IllegalStateException
if invoked before callingnext()
norprevious()
or after the last call tonext()
orprevious()
, that is, the cursor value is either -1 or the list size.
private static void listIteratorAdd() { LinkedList<String> words = new LinkedList<>(); print(true, words); // EMPTY LINKED LIST System.out.println(); ListIterator<String> listIterator = words.listIterator(0); // STILL EMPTY listIterator.add("You"); //listIterator.next(); // UNCOMMENTING WILL THROW NoSuchElementException listIterator.add("Learn"); listIterator.add("Java"); if (listIterator.hasNext()) { // THIS BLOCK WILL BE IGNORED /* REMEMBER, IT ADDS BEFORE THE CURSOR */ System.out.println("It won't get here!"); } while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); if (listIterator.previousIndex() == 0) { // IF PREVIOUS INDEX == FIRST ELEMENT // IF PREVIOUS INDEX IS -1, THERE IS NO ELEMENT LEFT // AND CALLING PREVIOUS WILL THROW AN EXCEPTION. System.out.println(listIterator.previous()); listIterator.add("Helps"); } } print(false, words); }
Output:
Before: Java Learn You Helps After: Helps You Learn Java!
3.7.1.10 void set(E e)
Replaces the last element returned by next or previous with the specified element passed as parameter. Invoking set(E e)
immediately after calling add(E e)
or remove()
and before calling next()
or previous()
will result in IllegalStateException
, this happens because both methods will set the lastReturned
variable to null.
- Parameter: e — the element with which to replace the last element returned by next or previous.
- Throws:
UnsupportedOperationException
if the list iterator does not support the set operation. - Throws:
ClassCastException
if the class of the specified element prevents the addition to this list. - Throws:
IllegalStateException
if invoked before callingnext()
norprevious()
or immediately after callingadd(E e)
orremove()
, and before callingnext()
orprevious()
or if the list is empty.
private static void listIteratorSet() { LinkedList<String> words = getWords(); print(true, words); ListIterator<String> listIterator = words.listIterator(0); while (listIterator.hasNext()) { String word = listIterator.next(); // listIterator.remove(); //UNCOMMENT FOR IllegalStateException System.out.println(word); listIterator.set(word.toUpperCase()); } print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Code Learn Hub Helps You Learn Java After: CODE LEARN HUB HELPS YOU LEARN JAVA!
3.7.2 Iterator<E> descendingIterator()
This method is just an adapter to provide a descending iterator which internally instantiates a list iterator passing the LinkedList
size, so, whenever you call hasNext()
it internally calls the list iterator hasPrevious()
method, in the same way if you call next()
, internally it invokes the list iterator previous()
method and it only offers the remove()
method in contrast to a list iterator which offers add()
, set()
and remove()
.
- Returns: a
DescendingIterator
instance.
private static void descendingIterator() { LinkedList<String> words = getWords(); print(true, words); Iterator<String> descendingIterator = words.descendingIterator(); while (descendingIterator.hasNext()) { System.out.println(descendingIterator.next()); descendingIterator.remove(); } /* THE ABOVE CODE IS EQUIVALENT TO THE ONE BELOW */ /* ListIterator<String> listIterator = words.listIterator(words.size()); while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); listIterator.remove(); } */ print(false, words); // EMPTY LINKED LIST BY NOW }
Output:
Before: Code Learn Hub Helps You Learn Java! Java Learn You Helps Hub Learn Code After:
3.7.3 Spliterator<E> spliterator()
We can use a Spliterator
to split a given collection into small subsets, so it becomes possible to perform some operations and or calculations on each one of the sets in separate threads by taking advantage of parallelism. We won’t dive into parallelism, nor will we dive into Spliterator
or its methods in this article.
- Returns: a
Spliterator
over the elements in the LinkedList.
private static void spliterator() { // A range large enough so it will be split. LinkedList<Integer> numbers = IntStream.range(0, 1050).boxed().collect(Collectors.toCollection(LinkedList::new)); print(true, numbers); Spliterator<Integer> spliterator = numbers.spliterator(); Spliterator<Integer> trySplit = spliterator.trySplit(); // MAY RETURN NULL System.out.println("Spliterator Get exact size if known: " + spliterator.getExactSizeIfKnown()); System.out.println("Spliterator Estimate size: " + spliterator.estimateSize()); // IT'LL EXECUTE THE ACTION IF THE ELEMENT EXISTS THEN RETURN TRUE, OTHERWISE FALSE. // IF THE ACTION RETURNS NULL, A NULL POINTER EXCEPTION IS THROWN System.out.print("Spliterator With Try Advance: "); while (spliterator.tryAdvance(x -> System.out.printf("%d ", x))); System.out.println(); // UNCHECKED! WE DIDN'T CHECK FOR NULL System.out.println("Try Split Get exact size if known: " + trySplit.getExactSizeIfKnown()); System.out.println("Try Split Estimate size: " + trySplit.estimateSize()); System.out.print("Try Split with for Each Remaining: "); // Performs the given action for each remaining element, sequentially in the current thread, // until all elements have been processed or the action throws an exception // forEachRemaining performs do { } while (tryAdvance(action)); internally. trySplit.forEachRemaining(x -> System.out.printf("%d ", x)); System.out.println(); print(false, numbers); }
Output:
Before: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049! Spliterator Get exact size if known: 26 Spliterator Estimate size: 26 Spliterator With Try Advance: 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 Try Split Get exact size if known: 1024 Try Split Estimate size: 1024 Try Split with for Each Remaining: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 After: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049!
4. Java LinkedList Inherited Methods
In this section we will cover some methods that the LinkedList does NOT override, instead, it uses the super class or interface methods and since some methods are purpose specific, we won’t cover them in this article, e.g. wait, notify, notifyAll, etc. Neither will we cover those that are deprecated.
4.1 Abstract Collection Methods
Methods inherited from the Abstract Collection Class.
4.1.1 boolean containsAll(Collection<?> c)
Iterates over the specified collection checking each element returned by the iterator to see if it is in this collection.
- Parameter: c — the collection to be checked for containment in the
LinkedList
. - Returns:
true
if theLinkedList
contains every element in theCollection
. - Throws:
ClassCastException
if the types of one or more elements in the specified collection are incompatible with this collection (optional). - Throws:
NullPointerException
if the specified collection contains one or more null elements and this collection does not permit null elements (optional), or if the specified collection is null.
private static void containsAll() { LinkedList<String> words = getWords(); LinkedList<String> subWords = new LinkedList<>(words.subList(0, 3)); print(true, words); print(true, subWords); // UNCOMMENT THIS SO containsALL WILL RETURN FALSE. // subWords.set(0, "CODE"); // Code is not equal to CODE. // IF words CONTAIN ALL ELEMENTS IN subWords, THEN true. if (words.containsAll(subWords)) { System.out.println("ALL ELEMENTS WERE CONTAINED!"); subWords.forEach(System.out::println); } }
Output:
Before: Code Learn Hub Helps You Learn Java! Before: Code Learn Hub! ALL ELEMENTS WERE CONTAINED! Code Learn Hub
4.1.2 boolean isEmpty()
Returns true
if the call to size()
yields 0.
- Returns:
true
if theLinkedList
is empty, that is, it has no elements.
4.1.3 boolean removeAll(Collection<?> c)
Removes from the LinkedList
all elements that exist in both (optional operation). After that, the LinkedList
will contain no elements in common with the specified collection. It is an A – B in Math Set Operations.
- Parameter: c — the
Collection
containing elements to remove from theLinkedList
. - Returns:
true
if this collection changes because of the call. - Throws:
UnsupportedOperationException
if the removeAll method is not supported by this collection. - Throws:
if the types of one or more elements in this collection are incompatible with the specified collection (optional).ClassCastException
- Throws:
NullPointerException
if the specified collection contains one or more null elements and this collection does not permit null elements (optional), or if the specified collection is null.
private static void removeALl() { LinkedList<String> words = getWords(); print(true, words); if (!words.isEmpty()) if (words.removeAll(words)) // true IF AT LEAST ONE ELEMENT IS REMOVED. print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After:
4.1.4 boolean retainAll(Collection<?> c)
Retains in the LinkedList
only the elements that are in the specified collection (optional operation). In other words, removes from the LinkedList
all elements that are not in the specified collection. It is an A ∩ B in Math Set Operations.
- Parameter: c — containing elements to retain in the
LinkedList
. - Returns:
true
if this collection changes because of the call. - Throws:
UnsupportedOperationException
if the removeAll method is not supported by this collection. - Throws:
if the types of one or more elements in this collection are incompatible with the specified collection (optional).ClassCastException
- Throws:
NullPointerException
if the specified collection contains one or more null elements and this collection does not permit null elements (optional), or if the specified collection is null.
private static void retainAll() { LinkedList<String> words = getWords(); LinkedList<String> subWords = new LinkedList<>(words.subList(0, 3)); print(true, words); print(true, subWords); if (words.retainAll(subWords)) System.out.println("ALL EQUAL ELEMENTS WERE RETAINED!"); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Before: Code Learn Hub! ALL EQUAL ELEMENTS WERE RETAINED! After: Code Learn Hub Learn!
4.1.5 String toString()
Returns a string representation of this collection. The string representation consists of a list of the collection’s elements in the order they are returned by its iterator, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (comma and space). Elements are converted to strings as by String.valueOf(Object)
.
- Returns: a string representation of this collection the
LinkedList
.
// Using toString() would conflict with Object toString() method. private static void toStringy() { LinkedList<String> words = getWords(); // IT IS UNNECESSARY TO CALL THE toString() METHOD EXPLICITLY // WE ARE DOING SO FOR PEDAGOGICAL PURPOSES System.out.println(words.toString()); }
Output:
[Code, Learn, Hub, Helps, You, Learn, Java]
4.2 Abstract List Methods
Methods inherited from the Abstract List Class.
4.2.1 List<E> subList(int fromIndex, int toIndex)
Returns a view of the portion of the LinkedList
between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty).
- Parameter:
fromIndex
— low endpoint (inclusive) of the sub-List. - Parameter:
toIndex
— high endpoint (exclusive) of the sub-List. - Returns: a view of the specified range within the
LinkedList
. - Throws:
IndexOutOfBoundsException
if an endpoint index value is out of range, that is,fromIndex
< 0 ortoIndex
> size. - Throws:
IllegalArgumentException
if the endpoint indices are out of orderfromIndex
>toIndex
.
private static void subList() { LinkedList<ProgrammingLanguage> pLanguages = getLanguages(); LinkedList<ProgrammingLanguage> subProgLanguages = new LinkedList<>(pLanguages.subList(0, 2)); // IF fromIndex AND toIndex ARE THE SAME, IT WILL RETURN AN EMPTY LIST. LinkedList<ProgrammingLanguage> emptyList = new LinkedList<>(pLanguages.subList(2, 2)); // UNCOMMENT TO GET AN IndexOutOfBoundsException: fromIndex < 0 AND OR toIndex > THE LIST SIZE. // LinkedList<ProgrammingLanguage> exception = new LinkedList<>(pLanguages.subList(-1, 5)); // UNCOMMENT TO GET AN IllegalArgumentException: fromIndex > toIndex. // LinkedList<ProgrammingLanguage> exception = new LinkedList<>(pLanguages.subList(4, 3)); // A SUBLIST OF ZERO AND THE LIST SIZE WILL RETURN THE EXACT SAME NUMBER OF ELEMENTS LinkedList<ProgrammingLanguage> pLanguages2 = new LinkedList<>(pLanguages.subList(0, pLanguages.size())); print(true, pLanguages); print(true, subProgLanguages); if (emptyList.isEmpty()) System.out.println("THIS LIST IS EMPTY!"); print(true, pLanguages2); pLanguages2.get(3).setLanguage("PHP"); // CHANGES WILL REFLECT ON BOTH LISTS // TRUE IF BOTH LISTS POINT TO SAME ADDRESS IN MEMORY System.out.println("Are we ==: " + (pLanguages == pLanguages2)); // UNCOMMENTING THE NEXT LINE WILL CAUSE EQUALS TO RETURN FALSE // pLanguages2.set(0, new ProgrammingLanguage("PYTHON")); // TRUE IF EACH ELEMENT POINTS TO THE SAME ADDRESS IN MEMORY System.out.println("Are we equals: " + pLanguages.equals(pLanguages2)); print(false, pLanguages); print(false, pLanguages2); }
Output:
Before: Java C# Swift C++! Before: Java C#! THIS LIST IS EMPTY! Before: Java C# Swift C++! Are we ==: false Are we equals: true After: Java C# Swift PHP! After: Java C# Swift PHP!
4.3 Abstract Sequential List Methods
Methods inherited from the Abstract Sequential List Class.
4.3.1 Iterator<E> iterator()
Actually, this method will invoke the listIterator
method in AbstractList
class which is no different from the one we have already covered, except it does not take an Integer as a parameter, it is defined in the AbstractList
class instead of the LinkedList
class and it won’t provide you with methods such as: previous()
, hasPrevious()
, add()
, set()
, previousIndex()
and nextIndex()
unless casted to a ListIterator
of the same type.
- Returns: an iterator over the elements in this list (in proper sequence).
private static void iterator() { LinkedList<String> words = getWords(); print(true, words); Iterator<String> iterator = words.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); iterator.remove(); } print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! Code Learn Hub Helps You Learn Java After:
4.4 Iterable Interface Methods
Methods inherited from the Iterable Interface.
4.4.1 default void forEach(Consumer<? super T> action)
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration if that order is specified.
- Parameter: action — The action to perform for each element.
- Throws:
NullPointerException
if the specified action is null.
private static void forEach() { LinkedList<String> words = getWords(); words.forEach(k -> System.out.println(k.toUpperCase())); // LAMBDA System.out.println(); words.forEach(System.out::println); // METHOD REFERENCE }
Output:
CODE LEARN HUB HELPS YOU LEARN JAVA Code Learn Hub Helps You Learn Java
4.5 Collection Interface Methods
Methods inherited from the Collection Interface.
4.5.1 default boolean removeIf(Predicate<? super E> filter)
Removes all the elements of this collection that satisfy the given predicate.
- Parameter:
filter
— a predicate which returns true for elements to remove. - Returns:
true
if any deletion occurs. - Throws:
NullPointerException
if the specified filter is null. - Throws:
UnsupportedOperationException
if it cannot perform the elements deletion from theLinkedList
.
private static void removeIf() { LinkedList<String> words = getWords(); print(true, words); words.removeIf(s -> s.startsWith("Y")); // IF ANY OF THE WORDS STARTS WITH A CAPITAL Y print(false, words); words.removeIf(s -> s.contains("e")); // IF ANY OF THE WORDS CONTAINS A SMALL e print(false, words); words.removeIf(s -> s.length() == 3); // IF THE length OF THE WORD EQUALS 3 print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Learn Hub Helps Learn Java! After: Hub Java! After: Java!
4.5.2 default <T> T[] toArray(IntFunction <T[]> generator)
Returns an array containing all the elements in this collection, using the provided generator function to allocate the returned array.
- Parameter: generator — a function which produces a new array of the desired type and the provided length.
- Returns: an array containing all the elements in the
LinkedList
. - Throws:
ArrayStoreException
if the runtime type of any element in theLinkedList
is not assignable to the runtime component type of the generated array. - Throws:
NullPointerException
if the generator function is null.
private static void toArrayWithIntFunction() { System.out.println("LINKED LIST"); LinkedList<ProgrammingLanguage> languages = getLanguages(); print(true, languages); // LINKED LIST ProgrammingLanguage[] languagesArray = languages.toArray(ProgrammingLanguage[]::new); System.out.println("ARRAY"); print(true, languagesArray); // ARRAY // SETTING WILL REFLECT ON BOTH languagesArray[3].setLanguage("Python"); // CHANGING LANGUAGE ON THE ARRAY System.out.println("LINKED LIST"); print(false, languages); }
Output:
LINKED LIST Before: Java C# Swift C++! ARRAY Before: Java C# Swift C++! LINKED LIST After: Java C# Swift Python!
4.5.3 default Stream<E> stream()
Creates a sequential Stream with the provided LinkedList. A sequence of elements supporting sequential and parallel aggregate operations, e.g. forEach, filter, map, average, etc. A sequence of those operations is called a pipeline. As with any stream, the stream is not executed until a terminal operation is invoked on it.
- Returns: a sequential Stream over the elements in the
LinkedList
.
private static void stream() { LinkedList<ProgrammingLanguage> languages = getLanguages(); print(true, languages); // LINKED LIST OF PROGRAMMING LANGUAGES // CREATE STREAM -> CHANGE INTO STRING -> SORT -> CONVERT INTO AN ARRAY (FINAL OPERATION) String[] array = languages.stream() // Stream<ProgrammingLanguage> .map(String::valueOf) // Stream<String> .sorted() // Sorted Stream in natural order .toArray(String[]::new); // Final Operation convert to Array. print(false, array); // RESULT: AN ARRAY OF STRINGS }
Output:
Before: Java C# Swift C++! After: C# C++ Java Swift!
4.5.4 default Stream<E> parallelStream()
Returns a possibly parallel Stream
with the LinkedList
as its source, but it is allowable for this method to return a sequential Stream
. When a stream executes in parallel, the Java runtime partitions the stream into multiple sub streams, aggregate operations iterate over and process these sub streams in parallel and then combine the results. Note that we use parallelStream()
over collection, if you already have a Stream, just call the parallel()
method instead.
- Returns: a possibly parallel Stream over the elements in the
LinkedList
.
First, we will add a helper method to calculate how much time the execution will take. Keep in mind this is not precise and one should not take it as a benchmark, it is just so we can have an idea of how much longer the sequential Stream takes to process the elements.
private static void calculateTimeTaken( LinkedList<ProgrammingLanguage> pLanguages, String streamingType, boolean isParallel) { long startTime = 0; long endTime = 0; startTime = System.currentTimeMillis(); Stream<ProgrammingLanguage> average = null; if (!isParallel) { average = pLanguages.stream(); // CREATES A SEQUENTIAL STREAM //average.parallel(); // TURN AN EXITING SEQUENTIAL STREAM INTO PARALLEL } else { average = pLanguages.parallelStream(); // CREATES A PARALLEL STREAM } // Do a bunch of nonsensical stuff that takes some time... var result = average.map(k -> k.getLanguage().substring(8)) .flatMapToInt(n -> IntStream.of(Integer.parseInt(n))) .average(); System.out.printf(streamingType + "%.2f\n", result.isPresent() ? result.getAsDouble()*-1 : -1); endTime = System.currentTimeMillis(); System.out.println("Time Taken: " + (endTime - startTime)); }
And here is our method
private static void parallelStream() { LinkedList<ProgrammingLanguage> pLanguages = new LinkedList<>(); for (int i = 1; i <= 100; i++) { pLanguages.add(new ProgrammingLanguage("Language-"+i)); } calculateTimeTaken(pLanguages, "Stream Average: ", false); calculateTimeTaken(pLanguages, "Parallel Stream Average: ", true); }
Output:
Stream Average: 50.50 Time Taken: 22 Parallel Stream Average: 50.50 Time Taken: 6
4.6 List Interface Methods
Methods inherited from the List Interface.
4.6.1 default void sort(Comparator<? super E> c)
Sorts the LinkedList
according to the order induced by the Comparator
. All elements must be mutually comparable using the comparator, that is, c.compare(e1, e2)
must not throw a ClassCastException
for any of the elements within it. If the specified comparator is null
then all elements must implement the Comparable interface and sorting will occur based on the elements’ natural.
- Parameter: c — the
Comparator
used to compare theLinkedList
elements. - Throws:
ClassCastException
if theLinkedList
contains elements that are not mutually comparable using the comparator. - Throws:
UnsupportedOperationException
if theLinkedList
‘s list-iterator does not support the set operation. - Throws:
IllegalArgumentException
(optional) if the comparator violates theComparator
contract.
private static void sort() { LinkedList<String> words = getWords(); print(true, words); // String class implements Comparable, so I don't need to use a Comparator. words.sort(null); print(false, words); LinkedList<ProgrammingLanguage> languages = getLanguages(); print(true, languages); // We haven't implemented the Comparable interface, we could have, but we didn't. // Either Lambda Expressions or Method Reference will work. languages.sort(Comparator.comparing(ProgrammingLanguage::getLanguage)); // UNCOMMENTING THE NEXT LINE WILL THROW AN EXCEPTION //languages.sort(null); print(false, languages); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: Code Helps Hub Java Learn Learn You! Before: Java C# Swift C++! After: C# C++ Java Swift!
4.6.2 default void replaceAll(UnaryOperator<E> operator)
Replaces each element of the LinkedList
with the result of applying the operator to that element.
- Parameter: operator — the operator to apply to each element.
- Throws:
UnsupportedOperationException
if this list is unmodifiable, implementations may throw this exception if an element cannot be replaced or if, in general, modification is not supported. - Throws:
NullPointerException
if the specified operator is null or if the operator result is a null value.
private static void replaceAll() { LinkedList<String> words = getWords(); print(true, words); // REPLACE ALL String LITERALS FOR LOWER-CASE ONES words.replaceAll(String::toLowerCase); print(false, words); // REPLACE ALL String LITERALS FOR UPPER-CASE ONES words.replaceAll(String::toUpperCase); print(false, words); // REPLACE ALL String LITERALS FOR THEIR FIRST LETTER words.replaceAll(s -> s.substring(0, 1)); print(false, words); }
Output:
Before: Code Learn Hub Helps You Learn Java! After: code learn hub helps you learn java! After: CODE LEARN HUB HELPS YOU LEARN JAVA! After: C L H H Y L J!
5. Conclusion
By now you should have a comprehensive understanding of how LinkedList
works in Java, how to use its methods thoroughly ,and how to make the most of it. You can find the source code on our GitHub page.