简体   繁体   中英

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>

I dont know if a HashMap<String, HashMap<String, Object>> can be a better option or not. (In this case the map be like a relation of 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.

// 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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