如何用Java创建2D地图?
我想要一个将两个字符串映射到一个字符串的映射。例如:map["MainServer","Status"]
返回“active”。在 Java 中最好的方法是什么?我应该使用包含另一个 HashMap 作为其元素的 HashMap 吗?
I would like to have a mapping which maps two string into one string. For example: map["MainServer","Status"]
return "active". What is the best way to do it in Java. Should I use HashMap which include another HashMap as its elements?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
拥有映射到映射意味着您正在执行双重查找(语义上和成本方面)。
这是你真正想要的吗?
您最好定义一个包含 X 字符串的 MapKeyPair 类,并为它们重写 equals 和 hashCode。
更一般地,如果该对具有实际含义或抽象,则通过适当命名的对象来表示它。
Having a map to a map means that you are doing a double lookup (semantically and in terms of cost).
Is this what you actually want?
You may be better off defining a MapKeyPair class that contains X strings, and overriding equals and hashCode for them.
More generally, if the pair has an actual meaning or an abstraction, represent it via an appropriately named object.
听起来您正在向服务器对象发送消息以获取返回值。
为什么不创建一个具有名称和状态(以及所有其他辅助属性)的 Server 类,对其进行设置,并将 servername 映射到 server?
然后,你做这样的事情。
It sounds like you're sending messages to a server object to get return values.
Why not create a Server class with a name and status (and all other secondary properties), set that, and map servername to server?
Then, you do something like this.
在我看来,唯一重要的信息是最后的价值。
在这种情况下,最简单的解决方案是将字符串组合成一个键字符串
map["MainServerStatus"]
如果您想获得“MainServer”的所有值,您可以迭代所有元素并过滤以字符串“MainServer”开头的元素。
这是一个非常基本和简单的解决方案,但是当您不想知道“MainServer”的所有元素时,您可以使用它。否则可能会减慢您的应用程序速度
It seems to me, that the only important information is the value at the end.
I this case the simplest solution is to combine the strings into one single key string
map["MainServerStatus"]
If you want to have all values for "MainServer" you could iterate over all elements and filter the ones, which are starting with the String "MainServer".
This is a very basic and simple solution but when you do not want to know all elements of "MainServer"so foten, you could use it. Otherwise it could slow down your application
如果对的总数很小,就简单一点:从第一个键到第二个Map的Map;第二个 Map 从第二个键到值。
如果对的总数很大,性能可能很重要。如果是这样,我建议采用与上面相同的解决方案,但选择具有最小预期范围的第一个键(例如,如果第一个键是数千个名称之一,第二个键是十个预定义状态之一,让第二个键成为您查找的第一个键)。
如果性能并不重要,请追求设计透明度:使用 Pair 类作为单个 Map 中的键。 (Pair 类足够有用,可以说您现在应该已经有了一个编写良好的类。)
If the total number of pairs is small, go simple: a Map from the first key to a second Map; the second Map goes from the second key to the value.
If the total number of pairs is large, performance might matter. If it does, I'd suggest the same solution as above, but choose as your first key the one with the smallest anticipated range (e.g., if the first key is one of thousands of names, and the second is one of ten predefined statuses, let the second key be the first one you look up).
If performance doesn't matter, go for design transparency: use a Pair class as the key in a single Map. (A Pair class is useful enough that you should arguably already have a well-written one by now.)