Along with other Java collections, there is a Linked List. You will want to use a parameterized constructor to work easier with Java Linked List.
LinkedList<String> list = new LinkedList<String>();
As a linked list, it has container elements which will store the data and allow you to navigate through it. We saw many of the methods used for a Linked List when we built it our self.
Adding Elements to the List
Java has the add method just as we would expect, but it also has additional ways to add elements, such as addFirst()
to add it to the front of the list, or addLast()
, which like add()
, appends the element to the end of the list.
// add an element to the end of the list
list.add("Hello");
// add an element to the front of the list
list.addFirst("World");
// add an element to the end of the list
// same as add() method
list.addLast("Again");
System.out.println(list);
If you run this code, when you print out the list, it shows it as a list of elements, much like you’d find in an array.
Note that add()
and addLast()
do the same thing and are basically aliases of one another.
Removing Elements from the List
Just as we can add items to a Linked List, we can also remove items from a Linked List. Java provides several ways to remove an element, or even all elements within a collection – removeAll()
.
remove()
and removeFirst()
removes the first, or head, element, returning it.
removeLast()
removes and returns the last element in the list.
You can also remove passing in an object to be removed, and remove based upon an index into the Linked List.
Finally, as you can see below, you can remove based upon finding the first occurrence as you see below.
// removes the first found occurance of the object
list.removeFirstOccurrence("World");
System.out.println(list);
Java Linked List was originally found on Access 2 Learn