开发者

How to create a 2D map in Java?

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 开发者_Python百科which include another HashMap as its elements?


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.


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.

Server server = map.get(serverName);
return server.getStatus();


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


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜