Working Of List Intreface and LinkedList Class In Java Collection

Introduction

This article explains how the List Interface class and LinkedList class in Java collections work.

List Interface class

It is a part of Collections. It contains methods to insert and delete elements in index basis. It is a factory of the ListIerator interface.

Some commonly used public methods of the List Interface are:

  1. object set (int index, Object element)
  2. object remove (int index)
  3. ListIterator listIterator()
  4. ListIterator listIterator (int x)
  5. void add (int index, Object element)
  6. boolean addAll (int index, Collection cln)
  7. object get (int Index position)

ListIterator Interface

This interface traverses the list elements in a forward and backward direction.

Some commonly used public methods are:

  1. boolean hasPrevious
  2. Object previous
  3. boolean hasNext()
  4. Object next()

Example

import java.util.*;

class ListInterfaceEx

  {

    public static void main(String args[])

      {

        ArrayList arylst=new ArrayList();

        arylst.add("Jaun");

        arylst.add("Shridu");

        arylst.add("Ramesh");

        arylst.add(1, "Suresh");

        System.out.println("At 2nd position the element are: "+arylst.get(2));

        ListIterator it=arylst.listIterator();

        System.out.println("Print the elements in forward direction...");

        while(it.hasNext())

          {

            System.out.println(it.next());

          }

        System.out.println("Print the elements in backward direction...");

        while(it.hasPrevious())

          {

            System.out.println(it.previous());

          }

      }

  }

Output

Fig-1.jpg

Introduction to the LinkedList class

It has the following features:

  • Can be used as a stack, list or queue.
  • It provides fast manipulation because shifting is not necssary.
  • It uses a doubly linked list for storing the elements.
  • No random access.
  • It can also contain duplicate elements.
  • Used to maintain insertion order.
  • Not synchronized.

Example

import java.util.*;

class LinkedListEx

  {

    public static void main(String args[])

      {

        LinkedList arylst=new LinkedList();

        arylst.add("Jaun");

        arylst.add("Shridu");

        arylst.add("Ramesh");

        arylst.add(1, "Suresh");

        Iterator it=arylst.iterator();

        while(it.hasNext())

          {

            System.out.println(it.next());

          }

      }

  }

Output

Fig-2.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all