LinkedList Class In UTIL Package Collection

Introduction

The Linked List class provides a linked-list data structure. It contains two constructors.

  • LinkedList(): Creates an empty linked list.
  • LinkedList(Collection c): Creates a linked list using the elements of the collection c.

Methods used

The linked list class contains its own methods in addition to the methods it inherits. The operations of the LinkedList class allow it to be used as a stack, queue or double-ended queue.

  • void addFirst(Object a): Inserts the object a at the beginning of the current list.
  • void addLast(Object a): Inserts the object a at the end of the current list.
  • Object getFirst(): Returns the first element in the current list.
  • Object getLast(): Returns the last element in the current list.
  • Object removeFirst():  Removes the first element from the current list.
  • Object removeLast():  Removes the last element from the current list.

Below source code illustrates the usage of the methods of the LinkedList interface.

import java.util.*;
class LinkedListOper {
    public static void main(String args[]) {
        LinkedList l = new LinkedList();
        l.add("Oracle");
        l.add("Java");
        l.add("PHP");
        System.out.println("The linked list after adding the first 3 elements is as follows:\n" + l + "\n");
        l.addFirst("Dot Net");
        l.addLast("Python");
        System.out.println("The Linked list after adding 2 more elements is :\n" + l + "\n");
        System.out.println("The Third element in the linked list is :" + l.get(2) + "\n");
        l.remove("PHP");
        System.out.println("\n The Linked list after removing the element 'PHP' is as follows:\n" + l + "\n");
        l.set(3, "AngularJS");
        System.out.println("\n The Linked List after changing the fourth element is as follows:\n" + l + "\n");
    }
}

The output appears as,

Summary

The Linked List class provides a linked-list data structure. It contains two constructors, namelyLinkedList() which creates an empty linked list. And LinkedList(Collection c) which also Creates a linked list using the elements of the collection c.


Similar Articles