Friday 18 April 2014

HashSet : hashCode : Get the Hash Code of the Map

public int hashCode()
Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set.

import java.util.*;

class HashSetHashCode{
 public static void main(String args[]){
   Set<String> mySet = new HashSet<String> ();
 int sum = 0;
    
   mySet.add("Hi");
   mySet.add("How are u");
   
   System.out.println("Hash code of the elements in the set is ");
   System.out.println("----------------------------------------");
   Iterator<String> iter1 = mySet.iterator();
   while(iter1.hasNext()){
    String str = iter1.next();
    System.out.print("\"" + str + "\" has the hash code ");
  System.out.println(str.hashCode());
  sum = sum + str.hashCode();
   }
 
   System.out.println("----------------------------------------");
 System.out.println("Sum Of Hash Codes of elements is " + sum);
   System.out.println("HashCode of the set is " + mySet.hashCode());  
 }
}

Output
Hash code of the elements in the set is
----------------------------------------
"Hi" has the hash code 2337
"How are u" has the hash code -1861319239
----------------------------------------
Sum Of Hash Codes of elements is -1861316902
HashCode of the set is -1861316902




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment