Wednesday, 30 November 2016

Program to demonstrate "LinkedList" class in Java's Collection Framework

The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list data structure. Following are the constructors supported by the LinkedList class.
  1. LinkedList( )This constructor builds an empty linked list.
  2. LinkedList(Collection c)This constructor builds a linked list that is initialized with the elements of the collection c.
LinkedList defines following methods:
  1. void add(int index, Object element) : Inserts the specified element at the specified position index in the list.
  2. boolean add(Object o) : Appends the specified element to the end of the list.
  3. void addFirst(Object o) : Inserts the given element at the beginning of the list.
  4. void addLast(Object o) : Appends the given element to the end of the list.
  5. void clear() : Removes all of the elements from the list.
  6. boolean contains(Object o) : Returns true if this list contains the specified element.
  7. Object get(int index) : Returns the element at the specified position in the list.
  8. Object getFirst( ) : Returns the first element in the list.
  9. Object getLast( ) : Returns the last element in the list.
  10. int size( ) : Returns the number of elements in the list.

PROGRAM
import java.util.LinkedList;
import java.util.List;

class LinkedListDemo {

 public static void main(String[] args) {

  List<String> p=new LinkedList<String>();
  p.add("Apple");
  p.add("Orange");
  p.add("PineApple");
  System.out.println("Element are ");
  
  for(int i=0;i<p.size();i++)
   System.out.println(p.get(i));
 }
}
OUTPUT
C:\>javac LinkedListDemo.java
C:\>java LinkedListDemo
Element are 
Apple
Orange
PineApple

No comments:

Post a Comment