Using two (or more) objects as a HashMap key

前端 未结 8 1191
借酒劲吻你
借酒劲吻你 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:15

    One can solve this issue using apache's commons collection lib's MultiKey class. Here is a simple example:

    import org.apache.commons.collections.keyvalue.MultiKey;
    
    HashMap map = new HashMap();
    MultiKey multiKey = new MultiKey(key1, key2);
    
    map.put(multikey,value);
    
    //to get 
    map.get(new MultiKey(key1,key2)); 
    

提交回复
热议问题