简体   繁体   English

在地图或对象中使用地图

[英]Use a Map in a Map or an object

I've a Map like this我有这样的地图

This class used as key这个类用作关键

class Key {
    private final String type;
    private final String qualifier;
    // getters, equals and hashCode
}

The map is HashMap<Key, Object>映射是HashMap<Key, Object>

I dont know if a HashMap<String, HashMap<String, Object>> can be a better option or not.我不知道HashMap<String, HashMap<String, Object>>是否是更好的选择。 (In this case the map be like a relation of keyType -> {keyQualifier -> value, otherQualifier -> value}) (在这种情况下,映射就像 keyType -> {keyQualifier -> value, otherQualifier -> value} 的关系)

Please leave examples请留下例子

I think your attempt is good.我认为你的尝试很好。 It's probably a bit faster faster (just one get() call) and more readable to access an object with your key object than.与使用键对象访问对象相比,它可能要快一点(只需一个 get() 调用)并且更具可读性。

// Complex key object
Map<Key,Object> map;
Object value = map.get(new Key(type, qualifier));

// 'Simple' key object, don't do this
Map<String, Map<String, Object> map;
Map<String, object> tmpMap = map.get(type); // that is actually confusing to read
Object value = tmpMap.get(qualifier));

But don't forget, hashCode() and equals() must be implemented correctly!但是不要忘记, hashCode() 和 equals() 必须正确实现!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM