/ Java  

Compare HashSet and TreeSet

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
  • HashSet is NOT synchronized. If multiple threads access a HashSet at the same time and threads modify the HashSet elements, the code must be used to ensure its synchronization
  • The elements of HashSet can be null

Characteristic of TreeSet

  • Elements in TreeSet is ordered. After the element is inserted, it will be arranged according to a specified order
  • TreeSet is NOT synchronized.
  • The elements of TreeSet can’t be null

Differences

  • HashSet is implemented by hash table. The data in HashSet is unordered and can be put into null, but only one null is allowed.
  • TreeSet is implemented by binary tree. The data in Treeset is sorted automatically, and null values are not allowed.
  • The values in TreeSet and HashSet can not be repeated, just like the only constraint in the database.
  • HashSet requires that the objects placed must implement the HashCode() method. The objects placed are identified by the hash code.
    • The String objects 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.
Powered By Valine
v1.5.2