- Both Hashset and Treeset implement the java.util.set interface
- Since they implement the set interface, by contract they do not allow any duplicates
- Both the implementations are not synchronized and hence they are not thread-safe. However, they can be made thread-safe by invoking the Collections.synchronizedSet() method.
- The main difference between the two is ordering, i.e. TreeSet maintains an ordered collection, whereas a HashSet does not maintain order
- If your implementation does not require any order and needs a faster collection, then go for HashSet.
- One other main important difference is HashSet does allow null, whereas, TreeSet, does not allow any null objects.
- The reson for the above would be that HashSet use equals() method to compare two objects in a Set, whereas, TreeSet uses compareTo() method which compare keys and hence it throws a NullPointerException if any null object is inserted into a TreeSet. (needs to be confirmed)
- Since they implement the set interface, by contract they do not allow any duplicates
- Both the implementations are not synchronized and hence they are not thread-safe. However, they can be made thread-safe by invoking the Collections.synchronizedSet() method.
- The main difference between the two is ordering, i.e. TreeSet maintains an ordered collection, whereas a HashSet does not maintain order
- If your implementation does not require any order and needs a faster collection, then go for HashSet.
- One other main important difference is HashSet does allow null, whereas, TreeSet, does not allow any null objects.
- The reson for the above would be that HashSet use equals() method to compare two objects in a Set, whereas, TreeSet uses compareTo() method which compare keys and hence it throws a NullPointerException if any null object is inserted into a TreeSet. (needs to be confirmed)