Cannot resolve method tailMap for TreeMap
Asked Answered
I

1

9

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!

Intuitivism answered 12/10, 2018 at 13:37 Comment(0)
F
9

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).

Firstly answered 12/10, 2018 at 13:47 Comment(2)
Indeed, SortedMap is the "highest" interface that defines the method. So as a rule of thumb, it is the one that should be used (just as a hint - the question was specifically about NavigableMap, so referring to that is fine here)Gurgitation
That is correct, SortedMap would be the best choice.Firstly

© 2022 - 2024 — McMap. All rights reserved.