class Key implements Serializable {
//overrides hashcode and equals methods
}
class HashSer {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Hashtable<Key,String> ht = new Hashtable<Key, String>();
Key key = new Key();
ht.put(key, "Value");
System.out.println("Entry: " + ht.get(key)); // retrieve using the key, works
// 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<Key, String> ht_in = (HashtableHashtable<Key, String>)(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(key) == null) // gets printed
System.out.println("Object was not found when retrieved using the key.");
}
}
|