Sunday, March 13, 2011

Bulk operations on map

The clear operation does exactly what you think it does: it removes all of the mappings from the Map. The putAll operation is the Map analogue of the Collection interface's addAll operation. In addition to its obvious use of dumping one Map into another, it has a second, more subtle, use. Suppose a Map is used to represent a collection of attribute-value pairs; the putAll operation, in combination with the standard Map constructor, provides a neat way to implement attribute map creation with default values. Here's a static factory method demonstrating this technique:
static Map newAttributeMap(Map defaults, Map overrides) {
    Map result =  new HashMap(defaults);
    result.putAll(overrides);
    return result;
}

No comments:

Post a Comment

Chitika