The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked list data structure. It has the following two constructors, described as follows:

LinkedList( ) 
LinkedList(Collection c) 
Copy the code

The first constructor builds an empty list of links. The second constructor builds a list of links initialized by elements in class c.

In addition to the methods it inherits, the LinkedList class itself defines some useful methods for manipulating and accessing lists. Use the addFirst() method to add elements to the head of the list; Use the addLast() method to add elements to the end of the list. Their form is as follows:

void addFirst(Object obj) 
void addLast(Object obj) 
Copy the code

Here, obj is the term being added.

Call the getFirst() method to get the first element. Call the getLast() method to get the last element. Their form is as follows:

Object getFirst( ) 
Object getLast( ) 
Copy the code

To remove the first element, use the removeFirst() method; To remove the last element, call the removeLast() method. Their form is as follows:

Object removeFirst( ) 
Object removeLast( ) 
Copy the code

The program below illustrates several of the methods LinkedList supports.

// Demonstrate LinkedList. 
import java.util.*; 
class LinkedListDemo { 
 public static void main(String args[]) { 
 // create a linked list 
 LinkedList ll = new LinkedList(); 
 
 // add elements to the linked list 
 ll.add("F"); 
 ll.add("B"); 
 ll.add("D"); 
 ll.add("E"); 
 ll.add("C"); 
 ll.addLast("Z"); 
 ll.addFirst("A"); 
 ll.add(1."A2"); 
 System.out.println("Original contents of ll: " + ll); 
 // remove elements from the linked list 
 ll.remove("F"); 
 ll.remove(2); 
 System.out.println("Contents of ll after deletion: " 
 + ll); 
 // remove first and last elements 
 ll.removeFirst(); 
 ll.removeLast(); 
 System.out.println("ll after deleting first and last: " 
 + ll); 
 // get and set a value 
 Object val = ll.get(2); 
 ll.set(2, (String) val + " Changed"); 
 System.out.println("ll after change: "+ ll); }}Copy the code

The output of the program looks like this:

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] 
Copy the code

Because LinkedList implements the List interface, call Add (Object) to append items to the end of the List, just as the addLast() method does. Insert the item at the specified location using the add(int, Object) form of the add() method, as in the example program that calls add(1, “A2”).

Notice how the third element in LL is changed by calling the get() and set() methods. To get the current value of an element, pass the subscript value that stores the element through the get() method. To assign a new value to the subscript position, pass the subscript and the corresponding new value through the set() method.