how to get the hashCode of a HashSet using the collections in java
Previous | Home | Next |
In this example we will see how can we get the hashCode of a HashSet.
For creating a HashSet we have to import the java.util package in which the HashSet class is defined. In this example we have created a class name CollectionExample in which we created a HashSet and added various elements to it.
For getting the hashCode of the HashSet we have used the hashCode() method on the object of the HashSet. This method returns the hashcode which is mostly the sum of the elements of the HashSet.
In this example we have created a HashSet and add some elements in it by using the add(Object obj) method on the object of the HashSet. Then for getting the hashcode of the HashSet thus created, we invoked the hashCode() method on the object of the HashSet. The following statement in the example does the same,set.hashCode();
where set is the HashSet object.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
HashSet<Integer> set=new HashSet<Integer>(); // creating a HashSet named set
set.add(1); // adding elements to the HashSet
set.add(3);
set.add(4);
set.add(5);
set.add(7);
set.add(1);
set.add(4);
set.add(7);
System.out.println("The contents of the set are:"); //displaying the contents of the HashSet
System.out.println(set);
System.out.println("The HashCode of the set is: "+set.hashCode()); // displaying the hash code of the set using the hashCode() method
}
}
The output of the code is as follows:
The contents of the set are:
[1, 3, 4, 5, 7]
The HashCode of the set is: 20
Previous | Home | Next |