Sunday, 27 April 2014

TreeSet : hashCode : 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 TreeSetHashCode{
 public static void main(String args[]){
   Set<String> mySet = new TreeSet<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

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment