Apr 2, 2012

Hashtable in Java Tutorial,Java Hashtable Collections

Hashtable in Java – Java Hashtable Tutorial


Hashtable in Java collections is used for storing key value pairs. There are many points to be noted about Hashtable in Java and we will discuss all of them:

How to create hashtable

The following program shows how to create hashtable and add key value pairs to it

package com.example;

import java.util.Hashtable;

/** This class is a demo for Java Tutorial on how to create hashtable in Java
*
* @author Extreme Java
*
*/
public class Test {


/** This method shows how to use hashtable in Java
*
* @param args
*/
public static void main(String[] args) {
Hashtable ht = new Hashtable();

ht.put("a", "z");
ht.put("b", "y");

System.out.println(ht.get("a"));
System.out.println(ht.get("b"));
}
}


Output:
z
y

Collision of key objects

If the hashcode for multiple key objects is same then there is collision scenario in the hashtable and the equals method of key class is used to determine the correct value object to be returned. The following code shows the collision scenario in a hashtable:

package com.example;

import java.util.Hashtable;

/** This class is a demo for Java Tutorial on how to create hashtable in Java
*
* @author Extreme Java
*
*/
public class Test {


/** This method shows how to use hashtable in Java
*
* @param args
*/
public static void main(String[] args) {

Example1 e1 = new Example1();
Example1 e2 = new Example1();

Hashtable ht1 = new Hashtable();

ht1.put(e1, "z");
ht1.put(e2, "y");

System.out.println(ht1.get(e1));
System.out.println(ht1.get(e2));

Example2 e3 = new Example2();
Example2 e4 = new Example2();

Hashtable ht2 = new Hashtable();

ht2.put(e3, "l");
ht2.put(e4, "m");

System.out.println(ht2.get(e1));
System.out.println(ht2.get(e2));
}
}

class Example1{

@Override
public int hashCode() {
return 1;
}
}

class Example2{

@Override
public int hashCode() {
return (int)((Math.random())*10);
}
}


output:
z
y
null
null

In the above code, Example2 class doesn't implement the equals-hashcode contract and hence unexpected results. However as in Example1 class's hashcode() method, the return of same hashcode everytime can hamper performance but will get expected results.

No comments:

Post a Comment