Java LinkedList Class

In this tutorial you will learn about Java LinkedList class. Linked list is a linear data structure that contains nodes. Node stores data and reference to the next node. Java provides us in built classes and methods for creating and handling of linked list. So using linked list in java so easy.

Also Read: Java Singly Linked List Implementation

Java LinkedList Class

Hierarchy of this class is:

Java.lang.object

  • java.util.AbstarctCollection
    • java.util.AbstractList
      • java.util.AbstarctSequentialList
        • java.util.LinkedList

Now we see those built-in methods of this class.

Constructors

This class has 2 constructors.

LinkedList(): create an empty linked list.

LinkedList(collection): It will create linked list with elements of the collection.

Methods

boolean add(element): this method will add element at the end.

void add(index, element): It will add element at the specified position.

void addFirst(element): element will be added at the first end of linked list.

void addLast(element): element will be added at the end of linked list.

clone(): this method will return replica of the linked list.

boolean contains(): it will be used for searching an element in linked list. If it found it will return true else false.

get(index): this method return the value present at the specified index.

getFirst(): it will return the first element of the linked list.

getLast(): it will return the last value of the linked list.

removeFirst(): it will remove first element from linked list.

removeLast(): it will remove last element form linked list

remove(val): it will remove specified node. If such node is not there then it will throw exception IndexOutOfBoundsException.

set(index, val): it will update the value at index to the specified value.

clear(): it will delete all the nodes.

size(): it will return the size of linked list.

These all methods will be helpful to use linked list easily. These methods will reduce the programming overhead of dealing with linkedlists.

Now we will see a program to demonstrate all these methods.

Program

Output

this is our linked list now
[1, 2, 3, 4, 5, 6]

7 is added first
list is[7, 1, 2, 3, 4, 5, 6]

8 is added at last
list is[7, 1, 2, 3, 4, 5, 6, 8]

element removed form first
list is[1, 2, 3, 4, 5, 6, 8]

element removed from last
list is[1, 2, 3, 4, 5, 6]

element at 2nd index is 3

first element in linked list 1

last element in linked list 6

size of linked list is 6

element found

all ements were deleted
list is now []

Comment below if you have any queries regarding Java LinkedList class.

Leave a Reply

Your email address will not be published. Required fields are marked *