Tuesday, May 24, 2016

Java LinkedList

There is two different ways to get the elements of a LinkedList.  Use the ListIterator method if you just need to process the elements in a sequential order.  If you need to address a specific element, it is much better to address the specific element in the list instead of getting an element and testing its field to see if you have reached the proper item.  Performance wise it will be O(n) vs. O(1) and we all know that O(1) would be a much more desirable performance goal. 

import java.util.LinkedList;
import java.util.ListIterator;
public class DebugLinkedListIterator {
public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<String>();
        linkedList.add("First");
        linkedList.add("Second");
        linkedList.add("Third");
        linkedList.add("Fourth");
        System.out.println("ListIterator Way: ");
        ListIterator<String> listIterator = linkedList.listIterator();
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }
        System.out.println("Loop Way: ");
        for (int i = 0; i < linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
        }
}
}
 

For someone dealing with concept for the first time, the best way to learn is to look at a single node in the debugger and trace the value changes.  This example should help with the process.

import java.util.LinkedList;
import java.util.ListIterator;


public class DebugLinkedListIterator {
public static void main(String[] args) {


        LinkedList<String> linkedList = new LinkedList<String>();
        linkedList.add("First");

        System.out.println("ListIterator Way: ");
        ListIterator<String> listIterator = linkedList.listIterator();
        System.out.println(listIterator.next());
        System.out.println(listIterator.previous());
        System.out.println(listIterator.next());
        System.out.println(listIterator.previous());
        System.out.println(listIterator.next());

        System.out.println("Loop Way: ");
        System.out.println(linkedList.get(0));
        System.out.println(linkedList.get(0));
        System.out.println(linkedList.get(0));
        System.out.println(linkedList.get(0));
}
}


 This screen shot is a direct copy of the running debugger, so you can see where the numbers came from in the image above.

No comments:

Post a Comment