The Internet is full of code examples on how you can create your own LinkedList class. Java provides and very easy to use class LinkedList. Following is an example on how to use a Java LinkedList.

import java.util.LinkedList;

public class LinkedListDemo {
   public static void main(String[] args) {   
      
      // initialize a LinkedList
      LinkedList link = new LinkedList();   
      System.out.println(link);   // empty linked list       

      // add elements
      link.add("linked");
      link.add("lists");
      System.out.println(link);

      // add an element in the first position   
      link.addFirst("My");
      System.out.println(link);

      // adding an element in a specific location
      link.add(1, new Integer(10));
      System.out.println(link);

      link.remove(2);
      System.out.println(link);

      System.out.println(link.size());
   }
}


output

[]
[linked, lists]
[My, linked, lists]
[My, 10, linked, lists]
[My, 10, lists]
3

First, LinkedList is initialized. The print statement prints an empty list. Then two elements are added and printed. An element can also be added such that it is the first element using addFirst(). An element can be added at a specific location by specifying an index. Indices start from 0. remove() removes an element from the linked list. link.size() prints the size of the list.

By master