Pacific-Design.com

    
Home Index

1. Algorithms

2. Hash Table

Algorithms / Hash Table /

Hashtable

package kduraj.myhashtable;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class MyHashTable {

    /*--------------------------------------------------------------------------------------------
     NULL is not allowed for key and value 
     Adding same keyword will overwrite value
     Collection is absolete
     */
    private static void testHashtable() {

        Hashtable balance = new Hashtable();
        String str;
        double bal;

        balance.put("Kevin", 100.10);
        balance.put("Thoma", 200.20);
        balance.put("Duraj", 300.30);
        balance.put("Kevin", 400.40);

        //--- Show all balances in hash table
        Enumeration names = balance.keys();
        while (names.hasMoreElements()) {
            str = (String) names.nextElement();
            System.out.println(str + ": " + balance.get(str));
        }

        System.out.println("-----------------------");
        System.out.println(balance.get("Kevin"));
    }
    /*--------------------------------------------------------------------------------------------
     NULL is allowed for key and value
     */

    private static void testHashMap() {
        Map<String, String> map = new HashMap<>();

        map.put("AAAA", "one");
        map.put("BBBB", "two");
        map.put("CCCC", "three");
        map.put(null, "four");
        map.put("DDDD", null);

        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String values = entry.getValue();
            System.out.println("Key = " + key + " => " + values);

        }
    }

    /*--------------------------------------------------------------------------------------------*/
    public static void main(String[] args) {

        testHashtable();        
        testHashMap();

    }
    /*--------------------------------------------------------------------------------------------*/
}

/*

Output

Thoma: 200.2
Kevin: 400.4
Duraj: 300.3
-----------------------
400.4
Key = null => four
Key = AAAA => one
Key = BBBB => two
Key = CCCC => three
Key = DDDD => null
*/