HashSet Class In Java

HashSet in Java

HashSet is first implemented class of set interface. As we know set not allow duplicate or order same as in.

  • First Implement Class of Set Interface.
  • The underlying data structure for HashSet is the HashTable.
  • As we know HashSet Class implements the Set Interface so duplicate values are not allowed.
  • Objects that you insert in HashSet are not guaranteed to be stored in same order. Objects are inserted based on their hash code.
  • NULL elements are allowed in HashSet class.
  • HashSet class also implements Serializable and Cloneable interfaces.

Constructors in HashSet:

   HashSet h = new HashSet();      
   Default initial capacity is 16 and default load factor is 0.75.

   HashSet h = new HashSet(int initialCapacity);  
   default loadFactor of 0.75
     
   HashSet h = new HashSet(int initialCapacity, float loadFactor);
     
   HashSet h = new HashSet(Collection C);

 

 

Methods of Java HashSet class:

Method Description
void clear()  remove all of the elements from this set.
boolean contains(Object o) return true if this set contains the specified element.
boolean add(Object o) adds the specified element to this set if it is not already present.
boolean isEmpty() return true if this set contains no elements.
boolean remove(Object o) remove the specified element from this set if it is present.
Object clone() return a shallow copy of this HashSet instance: the elements themselves are not cloned.
Iterator iterator() return an iterator over the elements in this set.
int size() return the number of elements in this set.

Example : -


import java.util.*;  

class TestHashSet{  

 public static void main(String args[]){ 

  //Creating HashSet and adding elements 
  HashSet<String> set=new HashSet<String>();  

  set.add("Tom");  

  set.add("Jerry");  

  set.add("Duck");  

  set.add("Tales");  

  set.add("Tom"); 

  //Traversing elements  

  Iterator<String> itr=set.iterator();  

  while(itr.hasNext()){  

   System.out.println(itr.next());  

  }  

 }  

} 

 

Output :  

 Tom
 Jerry
 Tales
 Duck

 

 

Related Articles

post a comment