Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
class HashSer {
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    Hashtable<Integer,String> ht = new Hashtable<Integer, String>();
    ht.put(new Integer(1), "Value");
    System.out.println("Entry: " + ht.get(1)); // retrieve using the key
	 
    // Serialize the Hashtable object
    FileOutputStream fos = new FileOutputStream("hashdata.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(ht);
    oos.close();
	 
    // Deserialize the Hashtable object
    FileInputStream fis = new FileInputStream("hashdata.ser");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Hashtable<Integer, String> ht_in = (Hashtable)(ois.readObject());
    ois.close();
	 
    if(ht_in.contains("Value")) // check if the object actually exists in the Hashtable
      System.out.println("Value was found in deserialized object.");
	 
    if (ht_in.get(1) == null)  // does not get printed
      System.out.println("Object was not found when retrieved using the key.");	 
  }
}

This particular problem can also be avoided by overriding the equals and the hashcode method in the Key class, though it is best to avoid employing hash tables that are known to use implementation defined parameters.

...