0

I have a problem with functionality of the next Sets and I really what to know what is the difference between TreeSet and HashSet in java and also What is the difference between TreeMap and HashMap.

Thanks.

jaavargasar
  • 15
  • 2
  • 7
  • I know how those sets works, but I want to know the difference between both. Thanks – jaavargasar Oct 31 '13 at 23:51
  • 1
    Read the documentation for each class. Then create a *different* post with a more refined question. (I would imagine that knowing how they work implies knowing the differences, but ..) – user2864740 Oct 31 '13 at 23:51
  • I know how to create those Sets and how I can fill that, but I don't see the difference, for me those Sets makes the same thing. – jaavargasar Oct 31 '13 at 23:57
  • 1
    The documentation discusses or gives clues to a number of issues that differ between the implementations: 1) ordering guarantees (or lack-of); 2) requirements for the items; 3) expected performance bounds; 4) additional methods not defined in the interface. – user2864740 Oct 31 '13 at 23:58
  • http://stackoverflow.com/questions/1463284/hashset-vs-treeset?rq=1 – user2864740 Nov 01 '13 at 00:00

2 Answers2

2

TreeMaps and TreeSets are similar to HashMaps and HashSets in almost every aspect except that the Tree versions keep the data in a sorted order (unlike the Hash versions in which the order is unspecified).

With TreeMap and TreeSet you can choose to use the 'natural' order of the content (assuming the content implements the Comparable interface), or alternatively you can supply your own Comparator to do the sorting for you.

One difference that catches people by suprise is that you can store null in HashMap and HashSet, but not (necessarily) in TreeSet or as a key in TreeMap.

rolfl
  • 17,539
  • 7
  • 42
  • 76
1

Hash set is much faster than tree set but offers no ordering guarantees. A tree Set organizes data in a tree through use of Comparator (natural ordering) and the hash Set organizes data in a hash table (using a hash function). One more thing you can store null values in Hash Set. while you can not store null in tree set it will throw exception null pointer Exception

sar
  • 1,277
  • 3
  • 21
  • 48
  • Technically you can store null in a `TreeMap` or `TreeSet` if you use a custom `Comparator` and the `Comparator` deals consistently with `null` values: http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#add(E) – rolfl Nov 01 '13 at 10:30