package samplePackage;

 

import .util.;

 

public class LinkedListExample {

public static void main(String args[]) {

//Creating linked list object

LinkedList<String> lref = new LinkedList<String>();

// Adding elements using add method

lref.add(“IDE”);

lref.add(“RC”);

lref.add(“WebDriver”);

lref.add(“Grid”);

System.out.println(lref);

// Adding element at first position in list using addFirst

lref.addFirst(“QTP”);

// Adding element at last position in list using addLast

lref.addLast(“Protractor”);

System.out.println(lref);

// Add elements at index 1 in list

lref.add(0, “Mercury”);

System.out.println(lref);

// Removing first item from list using removeFirst method

lref.removeFirst();

// Removing last item from list using removeLast method.

lref.removeLast();

System.out.println(lref);

// Removing item from list using value

lref.remove(“Two”);

System.out.println(lref);

// Removing item from list using index

lref.remove(3);

System.out.println(lref);

// Get item from list using index

System.out.println(lref.get(0));

// Set item at given index in list

lref.set(3, “New Entry”);

System.out.println(lref);

// We have four ways to print all the values of linked list

System.out.println(“====== For Loop starts here ======”);

for(int l=0; l<lref.size(); l++) {

System.out.println(lref.get(l));

}

System.out.println(“====== For Loop ends here ======”);

System.out.println(“====== For Each starts here ======”);

for(String str:lref) {

System.out.println(str);

}

System.out.println(“====== For Each ends here ======”);

System.out.println(“====== Iterator starts here ======”);

Iterator <String> it = lref.iterator();

while(it.hasNext()){

System.out.println(it.next());

}

System.out.println(“====== Iterator ends here ======”);

System.out.println(“====== While starts here ======”);

 

int num=0;

while(lref.size()>num){

System.out.println(lref.get(num));

num=num+1;

}

System.out.println(“====== While ends here ======”);

}

}



Source link https://www.softwaretestingmaterial.com/linkedlist-in-java/

LEAVE A REPLY

Please enter your comment!
Please enter your name here