1

So I wrote a code that stores reminders. I used a Hashtable to store the reminders. The key of the Hashtable is a Date object and the value is a String which represents the reminder content. It's all working great. I need to save the Hashtable to a file(file name should be provided by the user). Also, I need to let the user to choose either to load the reminders from an existing file or make a new Hashtable of reminders and save it in the end in another file. What's the best way to do that?

Losnikov
  • 87
  • 5
  • I guess serialization would do the job – Lev Leontev May 23 '19 at 19:44
  • Possible duplicate of [Can we write a Hashtable to a file?](https://stackoverflow.com/questions/2808277/can-we-write-a-hashtable-to-a-file) – rghome May 23 '19 at 19:55
  • "The best way" is for you to decide. Should it be a binary file (serialized objects) or a text file? If text file, what format would you like? Properties file? CSV file? XML file? JSON file? Something else? Question is primarily opinion-based (what is "best") and/or too broad. – Andreas May 23 '19 at 21:15

1 Answers1

0

As long as the types of objects used for keys and values implement "Serializable" interface, you can serialize the HashTable.

E.g. if your hashtable is Hashtable<KeyType, ValueType>; both KeyType and ValueType must implement Serializable

Here's a good tutorial on serialization in Java: https://www.tutorialspoint.com/java/java_serialization.htm

Please note that you can write your own custom serialization and deserialization methods, to convert to any format you want; if Java's default one somehow isn't OK for you.

DVK
  • 126,886
  • 32
  • 213
  • 327
  • Which class should implement Serializable? The one with the Hashtable? – Losnikov May 23 '19 at 19:51
  • @Losnikov - Hashtable itself already does. But HashTable maps one class (the key) to another (value) - both of THOSE, have to be Serializable too. E.g. if your values are random class you wrote; they won't be Serializable; if they are a String, they would be. – DVK May 23 '19 at 19:54
  • I mean, which class' signature in the package should be public class implements Serializable? – Losnikov May 23 '19 at 20:02
  • @Losnikov Since you said `Hashtable`, all 3 are already serializable. --- I would however suggest using a text file instead, i.e. format the dates as strings, create a `Properties` object with the mappings and save that. – Andreas May 23 '19 at 21:17