Using your own hashfunction in a HashTable

You can tweak the distribution in your Hashtable by overriding the hashCode method (defined in the Object class). Notice that in Hashtable.java, the hashCode is AND’ed with 0x7FFFFFFF (the maximum positive int, 2^31-1) to prevent storing at a negative array index.

Here’s an example:

Main.java:

import java.util.*;

public class Main extends Thread
{
   public static void main(String []args) throws Exception {
      Hashtable ht1 = new Hashtable();
      for (int i=0; i<10; i++) {
         ht1.put(new MyObject1(i), new Object());
      }
      output(ht1); 
 
      Hashtable ht2 = new Hashtable();
      for (int i=0; i<10; i++) {
         ht2.put(new MyObject2(i), new Object());
      }
      output(ht2);       
   }
 
   public static void output(Hashtable ht) {
      Enumeration keys = ht.keys();
      while (keys.hasMoreElements()) {
         System.out.print(keys.nextElement() + " ");
      }
      System.out.println();
   }
}
 
class MyObject1
{   
   int v;
 
   public MyObject1(int v) {
      this.v = v;
   }
 
   public String toString() {
      return "" + v;
   }
}
 
class MyObject2
{   
   int v;
 
   public MyObject2(int v) {
      this.v = v;
   }
 
   public String toString() {
      return "" + v;
   }
 
   public int hashCode() {
      return v;
   }
}

outputs:

2 9 5 4 0 7 1 6 8 3
9 8 7 6 5 4 3 2 1 0