Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!