I have a Hashtable<string,string>
, in my program I want to record the values of the Hashtable to process later.
My question is: can we write object Hastable to a file? If so, how can we later load that file?
In separate chaining, each element of the hash table is a linked list. To store an element in the hash table you must insert it into a specific linked list. If there is any collision (i.e. two different elements have same hash value) then store both the elements in the same linked list.
Hashmap vs Hashtable It is thread-safe and can be shared with many threads. HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value. HashMap is generally preferred over HashTable if thread synchronization is not needed.
A hash table is also either mutable or immutable; immutable tables support constant-time functional update. A hash table can be used as a two-valued sequence (see Sequences). The keys and values of the hash table serve as elements of the sequence (i.e., each element is a key and its associated value).
A hashtable is a data structure, much like an array, except you store each value (object) using a key.
Yes, using binary serialization (ObjectOutputStream
):
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(yourHashTable);
oos.close();
Then you can read it using ObjectInputStream
The objects that you put inside the Hashtable
(or better - HashMap
) have to implement Serializable
If you want to store the Hashtable
in a human-readable format, you can use java.beans.XMLEncoder
:
FileOutputStream fos = new FileOutputStream("tmp.xml");
XMLEncoder e = new XMLEncoder(fos);
e.writeObject(yourHashTable);
e.close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With