Monday 24 March 2014

Get Hash Code of the set

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 SetHashCode{
 public static void main(String args[]){
   Set<String> mySet = new HashSet<String> ();
    
   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.println("\"" + str + "\" has the hash code " + str.hashCode());
   }
   System.out.println("----------------------------------------");
   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
----------------------------------------
HashCode of the set is -1861316902

As you observe the output, Has code of the set is “-1861316902” which is the sum of hashcodes(2337 + -1861319239) of the elements in the set.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment