Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top