Using two (or more) objects as a HashMap key

前端 未结 8 1213
借酒劲吻你
借酒劲吻你 2020-12-13 21:51

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 us

8条回答
  •  难免孤独
    2020-12-13 22:19

    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:

    class KeyHolder {
        public final String key;
        public final Object storeMe;
    
        public KeyHolder(String key, Object storeMe) {
            this.key=key;
            this.storeMe=storeMe;
        }
    
        public equals(Object o) {
            return (o instanceof KeyHolder && ((KeyHolder)o).key.equals(key));
        }
    
        public hashcode() {
            return key.hashCode();
        }
    }
    

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

提交回复
热议问题