Java Java Data Structures Efficiency! Design the UI

HashMap order isn't guaranteed. Won't menu options appear in different order each time program is run?

If a HashMap structure holds the menu options and corresponding prompt actions, the order of options written to the screen will be different (or at least not guaranteed to be the same) each time the program is run. Shouldn't we use a TreeMap instead?

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Hi Adiv!

Nice attention to detail! TreeMap will make things alphabetical. LinkedHashMap will ensure the order added is maintained.

I don't remember if we swing back and fix that or not, but if not, LinkedHashMap is probably the way to go.

I'll add something to the teacher's notes.

Thanks!

Thank you. And now I see that, as you have pointed out, LinkedHashMap would be the preferred option because it preserves entries in the order in which they were added, whereas the TreeMap will sort its contents according to the data type it stores, e.g. alphabetically for Strings and sequentially for ints. We would not necessarily want the menu options to appear alphabetically in most cases. Thanks again!