Monday, February 16, 2015

LinkedList

The below Example explains about linked list and the associated methods.The main difference between arraylist and linkedlist is in the usage.
arraylist is better used for searching the element, while linked list is used for inserting deleting.


package Example1;

import java.util.LinkedList;

public class LInkedList {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		LinkedList linkedlistone=new LinkedList();//gerneric linkedlist
		LinkedList names=new LinkedList();//LinkedList specific to String
		
		//adding elements
		names.add("Jill");
		names.add("Jack");
		names.add("Roy");
		
		//Display elements
		
		for(String lists:names){
			System.out.println(lists);
		}
		//get a particular index
		System.out.println("Get the list as the index mentioned "+ names.get(2));
		
		//Get the first value
		System.out.println("Get the first value "+names.getFirst());
		
		//Get the last value
		System.out.println("Get the last value "+names.getLast());
		
		//copy of the linkedlist
		LinkedList newlist=new LinkedList(names);
		System.out.println("New linked list same as names "+newlist.toString());
		
		//check if a element exist
		if(newlist.contains("Jill")){
			System.out.println("Jill is present in the list");
		}
		//Check all as the othe list
		if(newlist.containsAll(names)){
			System.out.println("Both the list matches");
		}
		//index
		System.out.println("Return the index value "+newlist.indexOf("Jack"));
		
		//peek - returns the first element
		System.out.println(newlist.peek());
		
		//Poll - returns teh first element and delete it from the list
		System.out.println(newlist.poll());
		
		for(String display:newlist){
			System.out.println("This is the element in the newlist "+display.toString());
		}
		//push
		newlist.push("Jack");
		newlist.push("derek");
		
		System.out.println(newlist.toString());
		
		//clear
		newlist.clear();
		System.out.println(newlist.toString());
		
	}

}


output:
Jill
Jack
Roy
Get the list as the index mentioned Roy
Get the first value Jill
Get the last value Roy
New linked list same as names [Jill, Jack, Roy]
Jill is present in the list
Both the list matches
Return the index value 1
Jill
Jill
This is the element in the newlist Jack
This is the element in the newlist Roy
[derek, Jack, Jack, Roy]
[]

>>>Final
------------------------------------------------------------------------------------------------------------