Last time we talked about TreeSet in Java: Java TreeSet. This blog is just to provide a quick summary of the comparison between HashSet and TreeSet.
Characteristic of HashSet
- The order of the elements cannot be guaranteed. The order stored may be different from the order of addition and may change later
HashSetis NOT synchronized. If multiple threads access aHashSetat the same time and threads modify theHashSetelements, the code must be used to ensure its synchronization- The elements of
HashSetcan be null
Characteristic of TreeSet
- Elements in
TreeSetis ordered. After the element is inserted, it will be arranged according to a specified order TreeSetis NOT synchronized.- The elements of
TreeSetcan’t be null
Differences
HashSetis implemented by hash table. The data inHashSetis unordered and can be put into null, but only one null is allowed.TreeSetis implemented by binary tree. The data inTreesetis sorted automatically, and null values are not allowed.- The values in
TreeSetandHashSetcan not be repeated, just like the only constraint in the database. HashSetrequires that the objects placed must implement theHashCode()method. The objects placed are identified by the hash code.- The
Stringobjects with the same content have the same hashcode, so the content cannot be repeated. But objects of the same class can be put into different instances.
- The