如何为插入HashMap的每个元素打印日志?

时间:2012-09-11 17:19:31

标签: hashmap

我需要使用一个接受散列map作为参数的API。

但是,每当我在地图中插入一个键的值时,都需要打印日志。通过从外部csv文件读取来分配键的值。

例如,

Map<String,String> myMap = new HashMap<String,String>();

myMap.put("nodeId", myMap.get("nodeIDForCreationOfTrackedAsset"));
myMap.put("templateAssetID", myMap.get("assetIdForServiceHistory"));
myMap.put("seqId", "{{db.WM_TS001.SeqNum}}");
myMap.put("badgeId", "{{db.WM_TS001.BadgeNum}}");
myMap.put("serialId","{{db.WM_TS001.SerialNum}}");

所以每当我使用myMap.put(key,value)时,它应该将日志打印到外部文件,如下所示

element nodeId is assigned to "value" successfully.
element seqId is assigned to  "value" successfully.
element templateAssetID is assigned to "value" successfully.
element badgeId is assigned to "value" successfully.
element serialId is assigned to "value" successfully.

是否有任何通用方法可以执行此操作,以便在遇到myMap.put(key,value)时可以通过程序打印日志。

1 个答案:

答案 0 :(得分:0)

最明显的方法是扩展HashMap,然后将myMap声明为新子类的对象。例如:

public class LoggingHashMap<K, V> extends HashMap<K, V> {

    @Overrides
    public V put(K key, V value) {
        Log.i("LOG", "put:" + key + ":" + value;
        return super.put(key, value);
    }
}

Map<String, String> myMap = new LoggingHashMap<String, String>();