Why does TreeMap
of type Map
not define the methods tailMap
or headMap
.
Map<String, String> map = new TreeMap<>();
map.tailMap(); //cannot resolve method tailMap
With explicit cast it works:
((TreeMap<String, String>) map).tailMap("a");
With NavigableMap
everything is fine:
NavigableMap<String, String> map1 = new TreeMap<>();
map1.tailMap("a");
If I'm right that's because of the interface Map
lacking corresponding methods, in spite of the face that the object map
is concrete implementation of class TreeMap
that certainly does possess the such methods.
Just looking for more detailed explanation.
Thanks!
The object of type TreeMap
does have the method tailMap
, but you are referencing it via a reference of type Map
, which does not expose the tailMap
method itself. That is why the compiler complains.
Note that Java is statically typed. This means that the compiler needs to make sure at compile time that there is a method to call regardless of the actual implementation.
Since you could have a Map
implementation that does not define the tailMap
method, the compiler won't allow you to invoke the tailMap
method on an object referenced via Map
.
Since the NavigableMap
interface defines the method tailMap
, you are able to invoke the method on any object referenced via NavigableMap
. This also applies if you use TreeMap
as reference type, since TreeMap
implements NavigableMap
. This is why the compiler does not complain in your second and third examples (the explicit cast and the NavigableMap
reference declaration).