Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between HashSet and TreeSet

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 439
    Comment on it

    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.

    1. 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); 
      
      

    2. 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]



    3. HashSet allows null values on the other hand TreeSet does not allow. TreeSet throws NullPointerException.



    4. Time Performance for the general operations like add,size of HashSet is constant. But for HashSet its log(n) time cost for the same.



    5. As we go to the speed, HashSet is very faster than TreeSet

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: