LinkedList in Java
LinkedList in java is a resizable array like ArrayList. There is no size limit in LinkedList. When you add new elements or items in the LinkedList, the size or capacity of LinkedList will grow like Java ArrayList. You can do many things like add new elements, remove elements, change elements, sort the elements etc. like ArrayList. Both ArrayList and LinkedList implements List interface. Thus, possibly all the methods you can use in the ArrayList can also be used in LinkedList.
Syntax
//non-generic or row types
LinkedList list = new LinkedList();
//Generic approach: (with wrapper types)
LinkedList<T> list = new LinkedList(); ////T stands for type but wrapper. Primitive is not supported.
//such as
LinkedList<String> list = new LinkedList();
Example of Creating, Adding and Accessing Elements of LinkedList
In this very first example, we will see how to create generic LinkedList, adding new elements to the LinkedList and accessing elements using index number.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> planets = new LinkedList<>();
planets.add("Earth");
planets.add("Jupiter");
planets.add("Saturn");
planets.add("Mars");
//accessing first element using get(index) method
System.out.println("First Element: "+planets.get(0)); //returns the first element
//access the fits el using getFirst method
System.out.println("First Element (using getFirst): "+planets.getFirst());
System.out.println("Second Element: "+planets.get(1));
System.out.println("Last Element: "+planets.get(planets.size() - 1));
//returns last el using getLast method
System.out.println("Last Element (using getLast): "+planets.getLast());
}
}
/**
* Output:
* First Element: Earth
* First Element (using getFirst): Earth
* Second Element: Jupiter
* Last Element: Mars
* Last Element (using getLast): Mars
*/
Iterating LinkedList
we can simply iterate or loop through LinkedList elements using for loop, enhanced for loop or built in Iterator interface.
Using For Loop
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> planets = new LinkedList<>();
planets.add("Earth");
planets.add("Jupiter");
planets.add("Saturn");
planets.add("Mars");
//iterating LinkedList elements using for loop
for (int i = 0; i < planets.size(); i++) {
System.out.println(planets.get(i));
}
}
}
/**
* Output:
* Earth
* Jupiter
* Saturn
* Mars
*/
Using Enhanced For Loop
//iterating LinkedList elements using enhanced for loop
for (String planet : planets) {
System.out.println(planet);
}
/**
* Output:
* Earth
* Jupiter
* Saturn
* Mars
*/
Using Iterator Interface
import java.util.Iterator;
//iterate planets elements using Iterator interface
Iterator<String> list = planets.iterator();
while (list.hasNext()){
System.out.println(list.next());
}
Note: Which approach should I use to iterate LinkedList? Usually it depends on requirements and performances. Specially, IDE suggests to use enhanced for loop to iterate Collection type elements. But, you can choose whatever prefer most.
LinkedList Built in Methods
Methods for LinkedList:
Methods | Return types | Description |
---|---|---|
add(E element) | boolean | Appends the specified element to the end of this list. |
add(int index, E element) | void | Inserts the specified element at the specified position in this list. |
addAll(Collection<? extends E> c) | boolean | Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. |
addAll(int index, Collection<? extends E> c) | boolean | Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. |
get(int index) | E (element type) | Returns the element at the specified position in this list. |
isEmpty() | boolean | Returns true if this list contains no elements. |
iterator() | Iterator(E) | Returns an iterator over the elements in this list in proper sequence. |
remove(int index) | E | Removes the element at the specified position in this list. |
removeAll(Collection<?> c) | boolean | Removes from this list all of its elements that are contained in the specified collection. |
removeIf(Predicate<? super E> filter) | boolean | Removes all of the elements of this collection that satisfy the given predicate. |
set(int index, E element) | E | Replaces the element at the specified position in this list with the specified element. |
size() | int | Returns the number of elements in this list. |
trimToSize() | void | Trims the capacity of this ArrayList instance to be the list's current size. |
toArray() | Object | Returns an array containing all of the elements in this list in proper sequence (from first to last element). |
contains() | boolean | Returns true if this list contains the specified element |
clone() | Object | Returns a shallow copy of this ArrayList instance. (The elements themselves are not copied.) |
equals() | boolean | Checks two lists are equal or not (returns true ir false) |
indexOf() | int | Returns the index of the first occurrence of the specified element in this list. |
indexOf() | int | Returns the index of the last occurrence of the specified element in this list. |
sort() | void | Sorts the list alphabetically or numerically in a specified order (Ascending or Descending) |
stream() | Stream | Returns a sequential Stream with this collection as its source. |
addFirst() | void | Insert new element at the beginning of the LinkedList. |
addLast() | void | Insert new element at the end of the list. |
getFirst() | type of list | Get the item of first position of the list. |
getLast() | type of list | Retrieve the last element of the list. |
removeFirst() | type of list | Remove the first element from the list. |
removeLast() | type of list | Remove the last element from the list. |
clear() | void | Remove all the elements from the list. |
clone() | Object | Returns a shallow copy of the list. |
poll() | E | Retrieves and then remove the first element of the list. |
peek() | E | Retrieves but doesn't remove the first element. |
Key Things to Note About Java LinkedList
- LinkedList is one kind of Collection Type in Java
- It is resizable Array and the implementation of the List interface
- You can create LinkedList generic or non-generic order.
- There is no size limit of LinkedList in java
- The capacity or size of LinkedList can grow when you add new elements in it
- The members of LinkedList are ordered, index based, mutable (new elements can be added or removed as well)
- LinkedList supports duplicate elements
- Allowed only wrapper types and only one type (Integer or String not both)
- LinkedList size can be modified unlike Java Array type
- There is no need to specify the size of LinkedList