Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Collections  RSS feed

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have spent alot of time getting to know Collections.

It would be good if someone could confirm my understanding is correct?

I want to choose an implementation that:
1. Allows no duplicate keys
2. Sorts keys into order automatically
3. May allow null value, but they should not be allowed.

My understanding is that the TreeSet would be perfect for this implementation because
1. Lists are no good as they allow duplicate elements
2. HashSet/HashMap is no good because it is unordered

As TreeSet meets all the above criteria i.e. allows no duplicate keys, sorts keys into order automatically and may allow null value it meets my needs.

Is my understanding correct so far?

If this is the case why then, do examples show a Map being used to add and remove elements from unsorted map the convert to sorted map before displaying elements? Why not just go straignt to using a TreeMap?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, your understanding about TreeSet/TreeMap is correct. Frankly, I don't know why the examples you are referring to don't use it. Where are those examples from?

One real live reason to still use a Hash implementation over a Tree implementation is when the performance of changing the data is much more important than the performance of retrieving the data in sort order. But this is only relevant for big data sets.
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ilja,

Many thanks for your quick response. Much appreaciated!

Where I saw that it was suggested that you build a Hashmap and convert it to a TreeMap later was when you only need the sorted version after the map is populated.

Jim's Pages => Java Pages => Collections Framework.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unfortunately, he doesn't give the reason for the "tip".

I'd only do that if it solved a specific performance problem.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!