Quantcast
Channel: Scratch Where It's Itching
Viewing all articles
Browse latest Browse all 73

TreeMap misuse

$
0
0
TreeMap is a very practical class when you want your Map to keep its keys ordered. Unless you don't know how it works.

I noticed this code recently in one of our projects:

private Map<Double, Limit> limits = new TreeMap<>();

Nothing special about the declaration. Just a standard TreeMap ordering on its Double key. There were other similar declarations next to this one where the maps were used correctly. So I guess our developer felt he could reuse the same pattern. Except that his map was not ordered quite the way he needed it to. So when retrieving values, he would do that:

  List<Entry<Double, Limit>> limitList = new ArrayList<>(limits.entrySet());
  Collections.sort(limitList, LIMIT_DESC_COMPARATOR);
  generateExecs(limitList);

At first, I thought that the comparator would do something clever by combining key and value comparison.

private static final Comparator<Entry<Double, Limit>> LIMIT_DESC_COMPARATOR = new Comparator<>(){
    @Overridepublic int compare(Entry<Double, Limit> o1, Entry<Double, Limit> o2) {if (o1.getKey() == 0)return -1;if (o2.getKey() == 0)return 1;return o2.getKey().compareTo(o1.getKey());
    }
  }

No luck with that. It uses only the key. And do you see that method generateExecs, where you pass a list of entries? Guess what, it uses only the values. All of this strange code comes from one problem: the developer did not know that you could pass a comparator directly into the TreeMap constructor for immediate ordering in the correct order.


Viewing all articles
Browse latest Browse all 73

Trending Articles