Showing posts with label getClass. Show all posts
Showing posts with label getClass. Show all posts

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();
    }
}



Thursday, September 24, 2009

Java - how to create and use an ArrayList

import java.util.*;
 
// related posts:
// old (but fast) school array
// Thread safe vectors
// 
// 


public class Main {
 
    public static void main(String[] args) {
 
        // arraylists do not require a size definition 
        // when you declare or instantiate. 
        // you can add to your hearts content 
        ArrayList al = new ArrayList();
 
        al.add("number one");
 
        // display the size of the ArrayList 
        System.out.println(al.size());
        // indicates:  1 
 
        // fill up with 10 
        for (int i=0; i<10; i++){
            // you'll notice that it just appends to 
            // the existing list.  "number one" remains 
            // and all the numbers are tacked on after 
            al.add(i);
        }
 
        // display all ten with foreach 
        //for (Object o:al 
        for (int i=0; i<al.size(); i++){
            System.out.println(al.get(i) + " is type " +
                    al.get(i).getClass().toString());
        }
 
        // you'll notice from the output that a Java ArrayList 
        // can have a mixture of object types.  Here we 
        // blend Integer and String 
    }
}