Friday, September 25, 2009

Java - Hashtable example - how to create and use

import java.util.*;

public class Main {

    public static void main(String[] args) {
        // a hashtable is like a dictionary

        // to put items into the hashtable you 
        // need a key and a value.  The keys must
        // be unique -- while the values can be
        // anything you like
        Hashtable ht = new Hashtable();

        // put new values into ht

        ht.put("name", "Steve");
        ht.put("warpFactor", 9);

        String s = "";
        // looping add
        for (int i=0; i<20; i++) {
            s = Integer.toString(i);
            s += " is a good number";
            ht.put(i, s);
        }

        // use the values in the hashtable

        System.out.println("I hear that " +
                ht.get("name").toString() +
                " has a Warp Factor of " +
                ht.get("warpFactor").toString());

        // outputs:
        // I hear that Steve has a Warp Factor of 9

    }
}


No comments:

Post a Comment