1

Possible Duplicate:
Hashset vs Treeset

Can you use HashSet and TreeSet interchangeably? If I exchanged TreeSet for Hashset and vice versa in a program what issues would there be? Im aware you need to implement Comparable for a TreeSet.

Community
  • 1
  • 1
BLL27
  • 921
  • 5
  • 13
  • 27
  • what do you mean by interchange? can you write a sample? – kosa Aug 22 '12 at 16:45
  • PS I have a general understanding of how both work (pros, cons etc) but just want to know if there are any other things I should look out for. – BLL27 Aug 22 '12 at 16:46
  • 3
    Follow this: http://stackoverflow.com/questions/1463284/hashset-vs-treeset – Jimmy Aug 22 '12 at 16:47
  • @thinksteep if I had a program that used HashSet and simply changed it to TreeSet what issues would there be. – BLL27 Aug 22 '12 at 16:47
  • @Dave That depends on the intention of the program! – adarshr Aug 22 '12 at 16:48
  • @adarshr If I had a very basic program that worked correctly using HashSet and I replaced HashSet for TreeSet would I expect it to work or would I have to make other changes? I know it is a vague question and the answer is probably yes unless I want an ordered set then would have to make changes to the program. Any other thoughts? – BLL27 Aug 22 '12 at 16:53

3 Answers3

3

If some API requires Set, it absolutely doesn't matter which implementation you pass. If it requires concrete type (unlikely), you can't mix them.

In general, they difference is in performance (HashSet is faster) but this shouldn't affect how your program behaves and in order. Order of items in HashSet is unpredictable. If your program relies on any such order, it should rather use LinkedHashSet or TreeSet.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Thanks Tomasz, it is a question from a tutorial I am working on and is very vague, I guess that could be the point of the question to test your knowledge of the scenarios where you should use HashSet and where to use a TreeSet. – BLL27 Aug 22 '12 at 16:56
2

HashSet and TreeSet are both Sets. They are mostly interchangeable, but keep in mind TreeSet is also a SortedSet and thus its elements must implement Comparable.

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
1

If you want your set to be ordered, you should use TreeSet. If you use a HashSet instead, you'll get unpredictable results for operations that rely on the ordering.

On another hand, a HashSet is much faster than a TreeSet if order is not something you worry about.

adarshr
  • 61,315
  • 23
  • 138
  • 167