0

I apologize if the seems trivial but I always get confused on proper programming techniques. Sometimes there are too many ways to do one thing.

I have a HashMap <String, String> to store most of my data. I have a double that I would like to store in the same map. My question is:

If possible is it better to convert the non string to a string and store it in the current data structure; or would it be better to store a HashMap<String, Object> and cast the data accordingly when it gets used?

In this example would it be better to convert the Double to a String to store in the HashMap<String, String>?

Or, store all the data in a HashMap<String, Object> map and access it by casting data like this?

    Double dub = (Double) map.get(doublekey);

I am using this in Android development and was wondering which is the preferred method of doing things.

4

1 回答 1

1

I would say there isn't a hard and fast rule here. Ideally you wouldn't have to make this choice. The real question is why do you have a random double that must be stored in your hash map? If this is a one-time thing then it's probably not a problem to just convert it to a string. If however, you anticipate many doubles as well as string which must be stored, perhaps a different approach would be best. Using the type Object will make things more difficult for you down the line because you can no longer assume there are only Strings in the hash map. If you do change it to Object make sure you carefully check for anywhere in your code which may assume that Object is a string.

于 2013-02-18T01:26:40.103 回答