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 an index basis. It is a factory of the ListIerator interface.
Some commonly used public methods of the List Interface are:
- object set (int index, Object element)
- object remove (int index)
- ListIterator listIterator()
- ListIterator listIterator (int x)
- void add (int index, Object element)
- boolean addAll (int index, Collection cln)
- 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:
- boolean hasPrevious
- Object previous
- boolean hasNext()
- 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
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 necessary.
- 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