freetimestudys@gmail.com          +91-7097633380
  Login Here                        

LinkedList

1) Introduced in 1.2 v
2) Duplicate objects are allowed
3) Null insertion is possible
4) Heterogeneous objects are allowed
5) The under laying data structure is double linked list.
6) Insertion ode is preserved.

LinkedList class methods:

void addFirst(int i, obj):
 This method adds the element obj at the first position of the linked list.
void addLast(int i, obj):
 This method appends the specified element to the end of list. 
element removeLast(): 
This method removes the last element from the list and returns it.
element remove(int i): 
This removes an element at the specified position “i” in the linked list. 
element getFirst(): 
This method returns the first element from the list.
 element getLast(): 
This method returns the last element from the list. 

LinkedList with generics

import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("a");
l.add("ratan");
l.add("anu");
l.add("aaa");
System.out.println(l.size());
}
}

intput and output

4

LinkedList program

import java.util.ArrayList;
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList ll=new LinkedList();
System.out.println(ll.size());
//add the elements to the LinkedList
ll.add("a");
ll.add(10);
ll.add(10.6);
ll.addFirst("venkat");
ll.addLast("anu");
System.out.println("original content :"+ll);
System.out.println(ll.size());
//remove elements from LinkedList
ll.remove(10.6);
ll.remove(0);
System.out.println("after deletion content :"+ll);
System.out.println(ll.size());
//remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deletion of first and last :"+ll);
//get and set a value
int a=(Integer)ll.get(0);
ll.set(0,a+"venkat");
System.out.println("ll after change:"+ll);
}
}

intput and output

0
original content :[venkat, a, 10, 10.6, anu]
5
after deletion content :[a, 10, anu]
3
ll after deletion of first and last :[10]
ll after change:[10venkat]