The LinkedList Class in java

The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue interfaces. It provides a linked-list data structure. LinkedList is a generic class that has this declaration:

class LinkedList<E>

Here, E specifies the type of objects that the list will hold. LinkedList has the two constructors shown here:

LinkedList( )

LinkedList(Collection<? extends E> c)

The first constructor builds an empty linked list. The second constructor builds a linked list that is initialized with the elements of the collection c.

Because LinkedList implements the Deque interface, you have access to the methods defined by Deque.

For example, to add elements to the start of a list you can use addFirst( ) or offerFirst( ). To add elements to the end of the list, use addLast( ) or offerLast( ). To obtain the first element, you can use getFirst( ) or peekFirst( ). To obtain the last element, use getLast( ) or peekLast( ). To remove the first element, use removeFirst( ) or pollFirst( ). To remove the last element, use removeLast( ) or pollLast( ).

Demonstrate LinkedList

import java.util.*;

class LinkedListDemo {

public static void main(String args[]) { // Create a linked list.

LinkedList<String> ll = new LinkedList<String>();

//Add elements to the linked list. ll.add("F");







ll.add(1, "A2");

System.out.println("Original contents of ll: " + ll);

//Remove elements from the linked list. ll.remove("F");


System.out.println("Contents of ll after deletion: "


//Remove first and last elements. ll.removeFirst(); ll.removeLast();

System.out.println("ll after deleting first and last: " + ll);

// Get and set a value.
String val = ll.get(2); ll.set(2, val + " Changed");

System.out.println("ll after change: " + ll);



The output from this program is shown here:

Original contents of ll: [A, A2, F, B, D, E, C, Z]

Contents of ll after deletion: [A, A2, D, E, C, Z]

ll after deleting first and last: [A2, D, E, C] ll after change: [A2, D, E Changed, C]

Because LinkedList implements the List interface, calls to add(E) append items to the end of the list, as do calls to addLast( ). To insert items at a specific location, use the add(int, E) form of add( )

Leave a Comment