简体   繁体   English

的Android HashMap <String, Object> 要么 <String, String>

[英]Android HashMap of <String, Object> or <String, String>

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. 我有一个HashMap <String, String>来存储我的大部分数据。 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? 还是存储一个HashMap<String, Object>并在使用时相应地转换数据会更好?

In this example would it be better to convert the Double to a String to store in the HashMap<String, String> ? 在此示例中,将Double转换为String以存储在HashMap<String, String>会更好吗?

Or, store all the data in a HashMap<String, Object> map and access it by casting data like this? 或者,将所有数据存储在HashMap<String, Object>映射中,并通过像这样转换数据来访问它?

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

I am using this in Android development and was wondering which is the preferred method of doing things. 我在Android开发中使用了此功能,并且想知道哪种方法是首选的方法。

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. 如果确实将其更改为Object,请确保仔细检查代码中可能假定Object是字符串的任何地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM