Friday, September 25, 2009

Java - how to create and use a LinkedList

import java.util.*;

public class Main {
    
    public static void main(String[] args) {
        LinkedList ll = new LinkedList();

        // add to linked list

        ll.add("first String object");

        // total items in the linked list
        System.out.println(ll.size());
        // indicates:  1

        // the list is not type specific
        // Strings and ints can coexist

        ll.add(22);

        // add ten more items
        for (int i=0; i<10; i++){
            ll.add(i);
        }

        String oType = "";
        // iterate through all existing items
        //  with for-each

        for(Object o:ll){
            oType = o.getClass().toString();
            System.out.println(o.toString() + 
                    ", is type: " + oType);
        }

        // remove items from list
        ll.removeFirstOccurrence(3);

        // remove the first item from the list
        ll.remove();

        // remove the last item from the list
        ll.removeLast();
    }
}



No comments:

Post a Comment