I don't understand how NavigableMap.floorEntry()
and ceiling Entry()
work.
Oracle simply writes about ceilingEntry(key):
Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key.
Experimentally I learned that if I define NavigableMap
with integer key (NavigableMap<Integer, Anything>
), floorEntry(keyArg)
and ceilingEntry(keyArg)
always return the entry with given argument (keyArg)*
I understand that - it works like floor and ceiling functions in math: those functions return closest integer (if given not integer argument), given an integer argument they always return this given argument.
I thought (based on floor/entry definition in math) that snippet below would return "integer"
1.0
, 2.0
, etc.
Double 2.0
is not an integer. But ceilingEntry(keyArg)
is of no use with Integer keys, if it also does not work with Double keys (also returning its argument key) then how is it used, what is the use of it and working use cases?
NavigableMap<Double, String> m = new TreeMap<>();
m.put(1.3, "hey");
m.put(1.5, "hey2");
m.put(1.62, "hey3"); // not this
m.put(1.6, "hey3"); // argument given to ceilingEntry
m.put(1.68, "hey3"); // not this
m.put(1.7, "hey4"); // not this
m.put(2.0, "hey4"); // not this
m.put(1.0, "hey4");
m.put(3d, "hey4"); // not this
m.put(0d, "hey4");
// WHAT THEN ???
System.out.println(m.ceilingEntry(1.6)); // OUTPUT: 1.6=hey3
// I guess, to get something different from argument
//I shall give something not equal to any key as argument
System.out.println(m.ceilingEntry(1.601)); // 1.62=hey3
I got it. Whatever the key type, if exactly such key is already present in the map, ceilingEntry would simply return its argument.
It would return anything different only if the given argument is NOT present within map (as key). In this case ceilingEntry would return closest key in the map (in case of ceilingEntry - searching in ascending order (towards positive infinity)).
So it is quite unlike pure math floor/ceiling
- java is not looking for closest integer, java is looking for the closest existing key. Java does not care, whether this closest key is integer or 0.000786
(which is closest to arguments like 0.000785
or0.7
)