I want to store certain objects in a HashMap. The problem is, usually you just use a single object as a key. (You can, for example, use a String.) What I want to do it to use multiple object. For example, a Class and a String. Is there a simple and clean way to implement that?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You could create a holder class that contains the class and string that you want as the keys.
Probably not the best solution, but a possibility.
Apache Commons Collections has a multikey map which might do the trick for you:
https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/keyvalue/MultiKey.html
It looks like it will handle up to 5 "keys".
One can solve this issue using apache's commons collection lib's
MultiKey
class. Here is a simple example:There are a few places where people suggest creating a "Key" class containing the others, I totally agree. Just thought I'd add a helpful hint.
If you use eclipse or netbeans, they have a nice option--you can tell Eclipse to create equals and hashcode methods based on one or more members. So you just select the member (or members) you want to retrieve by and NB creates most of the code you'd need to write for you.
of course when I just want to retrieve by one object, I often just delegate the hashcode and equals methods to that object (delegating equals might be problematic because it would mean that one of your "Key holder" classes would be equal to the object that is it's key, but that's pretty easily fixed (and wouldn't usually effect anything anyway)
so off the top of my head:
That's all there is to it, and eclipse will do the last two for you if you ask it to.
By the way, I know that I have public members, a public final member is exactly the same thing as having a getter--not really a terrible idea. I'm starting to use this pattern on small utility classes like this a lot more lately. If the member wasn't final, it would be worse because it would be like having a setter (Something I try to avoid these days).
You key must implement the hashCode and equals. If it is a SortedMap, it must also implements the Comparable interface
The easiest way that I know of is to make a wrapper class and override hashmap and equals. For instance:
OF course, I would recommend using a StringBuilder and whatever else, but this way you have overridden the equals and hashcode, thereby allowing a hash and equality check on your multiple keys.
Also, I would recommend making the objects immutable (not editable) for safety's sake, but that is purely preference.