...
Wiki Markup |
---|
This noncompliant code example uses the {{Key}} class as the key index for the {{Hashtable}}. The {{Key}} class may or may not override {{Object.equals()}} but it distinctly does not override {{Object.hashCode()}}. According to the Java API \[[API 2006|AA. Bibliography#API 06]\] class {{Hashtable}} documentation |
...
Code Block | ||
---|---|---|
| ||
class Key implements Serializable { // OverridesDoes hashcodenot and equals methodsoverride hashCode() } 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 = (Hashtable<Key, String>)(ois.readObject()); ois.close(); if(ht_in.contains("Value")) // Check whether 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."); } } |
...
This problem can also be avoided by overriding the equals()
and the hashcode()
method in the Key
class, though it is best to avoid serializing hash tables that are known to use implementation defined parameters.
...