Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NavigableMap vs. SortedMap?

Tags:

Is there any reason to use SortedMap instead of NavigableMap, besides the JVM version? (NavigableMap has only been there since 1.6; SortedMap has been there since 1.2)

I'm trying to find the value with the greatest key such that key <= reference key K0. I can't seem to figure out how to do this with a SortedMap (if it were strictly <, then I'd call headMap() and then lastKey() and then get()), but NavigableMap.floorEntry() seems to be exactly what I need.


clarification: just as an example, I'm handling sparse ranges of version numbers with different behavior models. The keys might be [0, 2, 5], so that version numbers 0 and 1 get handled by the value at key #0, version numbers 2-4 get handled by the value at key #2, and version numbers >= 5 get handled by the value at key #5.

like image 295
Jason S Avatar asked Jan 19 '11 20:01

Jason S


People also ask

What is a NavigableMap?

NavigableMap is an extension of the SortedMap collection framework. It is used to arrange the elements in a uniform fashion. NavigableMap has different methods to iterate over the elements in the Map.

What is difference between map and SortedMap?

Map allows no duplicate values. The keys in a map objects must be unique. Java collection framework allows implementing Map interface in three classes namely, HashMap, TreeMap and LinkedHashMap. SortedMap is a special interface for maintaining all the elements in a sorted order.

What is navigational map in Java?

The NavigableMap interface is a member of the Java Collection Framework. It belongs to java. util package and It is an extension of SortedMap which provides convenient navigation methods like lowerKey, floorKey, ceilingKey and higherKey, and along with this popular navigation method.


1 Answers

Personally, I'm a big believer in using the least specific interface that provides you with what you need. This makes your intentions clearer and places less restrictions on your possible implementations.

Most developers want Sorted collections for iteration purposes and perhaps for random access performance. I've seen very few cases where I needed a close element.

If you need that functionality, go ahead. I think that TreeMap actually implements NavigableMap. But when you don't need it, why restrict yourself?

like image 144
Uri Avatar answered Sep 23 '22 09:09

Uri