简体   繁体   中英

How do you declare a TreeMap - SortedMap or Map?

I have written some code that works fine but I am confused about the correct way to declare a TreeMap.

If SortedMap is a subinterface of Map then is it okay to just use Map if the code is working okay? Is SortedMap even necessary if TreeMap works fine with Map?

Should it be:

private Map<String, List <Bus>> map = new TreeMap<String, List <Bus>>();

or

private SortedMap<String, List <Bus>> map = new TreeMap<String, List <Bus>>();

Thanks. Sorry this is so basic - I am new to Java.

I've used SortedMap to inform others that it is already sorted. Using Map is OK too.

private Map<String, List <Bus>> busTimetable = new TreeMap<String, List <Bus>>();

除非您有充分的理由,否则请始终使用最高级别的界面。

The answer to your question depends on your usage. By default, you should simply program to the data type's interface (ie Map ). If SortedMap provides methods that you will be using that aren't declared in Map , then program to SortedMap .

It depends upon your requirement and design whenever possible use the highest level of abstraction that is Map. The reason is say you are creating a service and it consume list of data and produce an output in a Map. some client may expect for sorted order of the data in the map and some other client may just need the data in the insertion order of the map if you use a specific interface SortedMap ; this kind of scenarion you can not handle using one service and you will end up creating two different api becuase one who is expecting sorted order you can just return an implementaion of TreeMap and one for insertion order you can use LinkedHashMap. So it's about how flexible is your program.

If you need to use specific SortedMap methods (like firstKey() / lastKey() /whatever...), it is mandatory to declare your reference as SortedMap . Otherwise, Map is the one I'd choose, if I'm only planning on using it as a Map , so I'll be able so switch implementations without any other change in the code.

I agree with other commenters that you use SortedMap if you use methods that aren't in vanilla Map . Also use SortedMap if you have use in an iterator or a for-each loop if they implicitly rely on sorted input.

If neither of these cases are true, you should also think about if you only need a vanilla Map , a HashMap may be a better choice. HashMap has O(1) access; TreeMap does not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM