I implemented the very nice sorting solution found here:
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>>
entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override
public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1;
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
The code seems to work great. However, FindBugs complains about this line:
sortedEntries.addAll(map.entrySet());
The complaint is:
Bug: Adding elements of an entry set may fail due to reuse of Map.Entry object in com.local.sem.util.MapUtil.entriesSortedByValues(Map)
The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.
Confidence: Normal, Rank: Troubling (14)
Pattern: DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS
Type: DMI, Category: BAD_PRACTICE (Bad practice)
Can anyone tell me what that means or if it's actually relevant to this particular code?