Hi,
I am explaining the difference between HashSet and TreeSet in Java.
First of all they both come from the same family. They implement the Set Interface.
- In HashSet, values store in random order. That means it is not sure that the element entered first will
be printed first.
HashSet hashSet= new HashSet();
hashSet.add("Remember");
hashSet.add("one ");
hashSet.add("Thing");
System.out.println(hashSet);
O/P: [one, Remember, Thing]
On the other hand in TreeSet, elements are sorted and it is the main characteristic of the TreeSet.
TreeSet<String> treeSet= new TreeSet<String>();
treeSet.add("Remember");
treeSet.add("one");
treeSet.add("Thing");
System.out.println(treeSet);
O/P: [One, Remember, Thing]
HashSet allows null values on the other hand TreeSet does not allow.
TreeSet throws NullPointerException.
Time Performance for the general operations like add,size of HashSet is constant.
But for HashSet its log(n) time cost for the same.
As we go to the speed, HashSet is very faster than TreeSet
0 Comment(s)