Sunday, June 21, 2009

Use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup

Using the FindBugs tool
Inefficient use of keySet iterator instead of entrySet iterator

This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup.
if(hashMap != null) {
Set set = hashMap.keySet();
Iterator it = set.iterator();
if (messageId!=null)
string += "MSGID=" + messageId + " ";
string += "TAG Details:{";
while(it.hasNext()) {
Integer intValue = (Integer)it.next();
string += GetTagName(intValue.intValue()) + "(" + intValue + ")=" + hashMap.get(intValue);
if (it.hasNext()) string += ", ";
}
}


instead use hashMap.entrySet()

No comments: