Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • HashSet in Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 307
    Comment on it

    Here I am writing a way to implement Hashset. HashSet creates hashtable to store the data. As it implements Set interface so it doesnt contains duplicate elements. It also extends AbstractSet class.


    We can implement HashSet by using different constructors :-

  • HashSet( ) :- This is the by default constructor.
  • HashSet(Collection c) :- Here hash set is initialized with collection c.
  • HashSet(int capacity) :- Here hashset is created with given integer capacity but capacity increase with increase of the elements.

    We add elements by using add(Object obj) method. We can clear hashset object using clear() method. We can create copy of the object using clone() method. We can also implement Iterator in hashset.


    Below is the implementation :-

    HashSet myHashSet = new HashSet(); 
      // add elements to the hash set 
      myHashSet.add("C"); 
      myHashSet.add("B"); 
      myHashSet.add("E"); 
      myHashSet.add("F"); 
      myHashSet.add("D"); 
      myHashSet.add("G"); 
      myHashSet.add("G"); 
    
      System.out.println(myHashSet); 
    
    
    } 
    } 
    

    Output :- [E, F, G, B, C, D]

Comment on it

 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: