How to Navigate LinkedList : Iterate through Elements

package JavaLinkedListExample;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;

/*
 * Here we will learn to navigate Linked list and display the elements in
 * Linked list using different available methods.
 */
public class NavigateLinkedList {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		LinkedList<String> linkedList = new LinkedList<String>();
		String objInput;

		System.out.println("Insert the elements in List(Enter exit to quit)");
		objInput = scanner.next();

		/*
		 * equalsIgnoreCase method compares this String to another String,
		 * ignoring case considerations.
		 */
		while (!objInput.equalsIgnoreCase("exit")) {
			linkedList.add(objInput);
			objInput = scanner.next();
		}

		/*
		 * There are two way we can navigate LinkedList. 1- Using Iterator 2-
		 * Using For Loop 3- Using Advance For Loop
		 */

		// Using Iterator
		System.out.println("nNavigating LinkedList using Iterator");
		System.out.println("Elements in LinkedList");
		Iterator iterator = linkedList.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

		// Using For Loop
		System.out.println("nNavigating LinkedList using For Loop");
		System.out.println("Elements in LinkedList");
		for (int i = 0; i < linkedList.size(); i++) {
			System.out.println(linkedList.get(i));
		}

		// Using Advanced For Loop
		System.out
				.println("nNavigating LinkedList using For Advanced For Loop");
		System.out.println("Elements in LinkedList");
		for (Object obj : linkedList) {
			System.out.println(obj);
		}

	}
}

 

By | 2012-09-25T03:37:37+00:00 September 25th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment