Thursday, 16 April 2015

Tutorial On Linked List In Java

The List interface extends Collection and declares the behaviour of collection stored in it.Elements can be inserted or removed in list using a define index.It can have same elements.

LinkedList:

Linked list have some very useful methods to store romove elements we can put elements in first or last index as I  done in this example same as that elements can be removed from first or last position.Remaining two functions is very important for retrieve purpose its signature is shown below.
Object getFirst()
ObjectgetLast()


METHODS OF LINKED LIST:


void add(int index,Object)

By using this method user can specify the specific position of object in an linkedlist.

boolean add(object ob)

This method add the element in the last position of an linked list.

boolean addAll(Collection c)

By using this method user can add all elements of  specified collection into a last position of linked list.

boolean addAll(int index,Collection c)

This method is also used to add collection in linked list but its add collection at specified position.

Void clear()

This method is applicable  when user want's to clear all elements of linked list.

Object get(int index)

This method can be used when user wants to get data from specific index in linked list.

int indexOf(Object ob)

This method returns the  index of specified object.

Object remove(int index)

This method remove the object at the specified position in an linked list.

Object set(int index, Object element)

This method is very useful when user want's to replace the specified object with a new one at a specified  position.

int size()

This method is used to check the size of specified linked list.

CODING:

import java.util.*;
class linkedlist
{
public static void main(String args[])
{
//Creating Linked List
LinkedList l1 = new LinkedList();
//Adding Elements To A Linked List
l1.add("No 2 Element");
l1.add("No 3 Element");
l1.add("No 4 Element");
l1.addFirst("No 1 Element");
l1.addLast("No 5 Element");
l1.add(5,"No 6 Elment");
System.out.println("Original Contents of l1:"+l1);
//Now Removing Elements From LinkedList
l1.remove("No 2 Element");
l1.removeFirst();
l1.removeLast();
System.out.println("Contents After Deleting :"+l1);
Object obj = l1.get(2);
String str = obj.toString();
l1.set(2,(str)+"Changed");
System.out.println("l1 after change :"+l1);
}
}

OUTPUT:


No comments:

Post a Comment