Sunday, November 3, 2013

How to use hashtables

Creating HashTables:

public void peopleInfo(String a) {
        // TODO Auto-generated method stub
        if (a == "evelyn") {
            Hashtable<String, String> information = new Hashtable<String, String>();
           
            information.put("Steve", "34 block 2");
            information.put("Sheryl", "34 block 5");
            information.put("Miranda", "34 F lane");

//How to pass hashtables to another method in another class
           PrintFunction printUp = new PrintFunction();
            printUp.printDetails(information);

}


ublic class PrintFunction {

    public String test_variable;

    public void printDetails(Hashtable<String, String> vars) {


//Checks if the HasTable contains the desired key.

        if (vars.containsKey("Miranda")) {

            System.out.println("Miranda stays in : " + vars.get("Miranda"));

// by doing vars.get("Miranda") you will get the corresponding value of this key in the HashTable.

        }

        if (vars.containsKey("Steve")) {

            System.out.println("Steve stays in : " + vars.get("Steve"));

        }
      
}

When the above is invoked from a main method, the output is:

Miranda stays in : 34 F lane

No comments:

Post a Comment