Friday, June 17, 2016

LinkedList Collection Class example java

LinkedList Class

A Linked list contains a group of elements in the form of nodes.Each node will have three fields---the data field contains data and the link fields contain references to previous and next nodes.

Linked List is very convenient to store data.Inserting the elements into the linked list and removing the elements from the linked list is done quickly and takes same amount of time.

LinkedList Class Methods

  • boolean add(element obj)
  • void add(int position,element obj)
  • void addFirst(element obj
  • void addLast(element obj)
  • element removeFirst()
  • element removeLast()
  • element remove(int position)
  • void clear()
  • element get(int position)
  • element getFirst()
  • element getLast()
  • element set(int position,element obj)
  • int size()
  • int indexOf(Object obj)
  • int lastIndexOf(Object obj)
  • Object[] toArray()
Program:


/**
 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class LinkedListApp
{
/**
* @param args
* @throws IOException 
* @throws NumberFormatException 
*/
public static void main(String[] args) throws NumberFormatException, IOException
{
LinkedList<String> ll=new LinkedList<>();
ll.add("America");
ll.add("India");
ll.add("japan");
System.out.println("list= "+ll);
int choice = 0;
int position;
String element;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(choice < 4)
{
System.out.println("LinkedList  Operation");
System.out.println("1 Add an element");
System.out.println("2 Remove an element");
System.out.println("3 Change an element?");
System.out.println("4 Exist");
System.out.println("Your Choice: ");
choice=Integer.parseInt(br.readLine());
switch (choice) 
{
case 1:
System.out.println("Enter element: ");
element=br.readLine();
position=Integer.parseInt(br.readLine());
ll.add(position - 1,element);
break;
case 2:
System.out.println("Enter position:");
position=Integer.parseInt(br.readLine());
ll.remove(position-1);
break;
case 3:
System.out.println("Eneter element?");
position=Integer.parseInt(br.readLine());
System.out.println("Eneter new element?");
element=br.readLine();
ll.set(position-1, element);
break;
default:
return;
}
}
}

}

Output:

list= [America, India, japan]
LinkedList  Operation
1 Add an element
2 Remove an element
3 Change an element?
4 Exist
Your Choice: 
1
Enter element: 
20


No comments: