Friday, August 28, 2009

Hash Table in Java

HashTable is implementation of key value pair data Structure in Java. You can store value using key and can retrieve value using key. Key should be unique.

Java Provides Class called HashTable which has following importan methods.

1. put(Object key, Object value) - used to store value into hashtable
2.get(Object key) - used to get values from hashtable using key.

Hashtable hashTable = new Hashtable():

hashTable.put('key1', 'value1'):
This method takes two arguments in which, one is the key and another one is the value for the separate key.

Map map = new TreeMap(hashTable):

This code creates the Map with the help of the instance of the TreeMap class.

package com.anuj.utils;

import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;

 * @author Anuj Patel
public class HashTableOperations {

    public static void main(String[] args) {

        Hashtable hashtable = new Hashtable();

        hashtable.put("key1", "value1");
        hashtable.put("key2", "value2");
        hashtable.put("key3", "value3");

        System.out.println("Value at Key 1 - " + hashtable.get("key1"));
        System.out.println("Value at Key 2 - " + hashtable.get("key2"));
        System.out.println("Value at Key 3 - " + hashtable.get("key3"));

        Map map = new TreeMap(hashtable);
Output : 
Value at Key 1 - value1
Value at Key 2 - value2
Value at Key 3 - value3
{key1=value1, key2=value2, key3=value3}
BUILD SUCCESSFUL (total time: 0 seconds)

Author : Anuj Patel
Blog :

No comments:

Post a Comment