Maybe my logic stopped working for a bit, but I find this behavior confusing. Suppose I have a TreeMap as follows:
TreeMap<Integer, Double> map = new TreeMap<Integer, Double>(Collections.reverseOrder());
map.put(123, 0.5);
map.put(678, 1.0);
map.put(567, 0.1);
int key = 100;
Now, I want to use the map.lowerEntry(key)
and according to the documentation of the getter:
Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
I would expect null
as a result, but the system call System.out.println("Lower than "+key+ " is "+map.lowerEntry(key));
produces Lower than 100 is 123=0.5
. If I use map.higherEntry(key)
which is documented as
Returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key.
then I get the desired result, but it is counter-intuitive based on the documentation. I guess calling the Collections.reverseOrder()
comparator on the TreeMap inverts the logic applied inside the map?
EDIT
Using a TreeSet I get consistent behavior (regarding the function names) when it is initialized with the Collections.reverseOrder()
comparator:
TreeSet<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());
set.add(123);
set.add(678);
set.add(567);
int key = 200;
System.out.println("Lower than "+key+ " is "+set.tailSet(key));
produces Lower than 200 is [123]
which I would expect.
Is this inconsistency between TreeMap and TreeSet normal? Can someone please explain please? Thank you.