AbstractSet hashCode() Method in Java with Examples
The AbstractSet.hashCode() method in Java AbstractSet is used to fetch the hash code value of a particular this AbstractSet. A set consists of a number of buckets to store the elements. Each bucket has a unique identity and when an element is inserted into a bucket, its hashcode is matched with the identifier of the bucket, and if its a match the element is stored successfully. This is how the hash code works.
Syntax:
AbstractSet.hashCode()
Parameters: The method does not accept any parameters.
Return Value: The method returns the hashcode value of the set.
Below programs are used to illustrate the working of AbstractSet.hashCode() Method:
Program 1:
// Java code to illustrate the hashCode() method import java.util.*; public class Abstract_Set_Demo { public static void main(String[] args) { // Creating an empty AbstractSet AbstractSet<String> abs_set = new HashSet<String>(); // Adding elements into the set abs_set.add( "Geeks" ); abs_set.add( "4" ); abs_set.add( "Geeks" ); abs_set.add( "Welcomes" ); abs_set.add( "You" ); // Displaying the AbstractSet System.out.println( "Initial Set is: " + abs_set); // Getting the hashcode value for the set System.out.println( "The hashcode value of the set: " + abs_set.hashCode()); } } |
Initial Set is: [4, Geeks, You, Welcomes] The hashcode value of the set-295204749
Program 2:
// Java code to illustrate the hashCode() method import java.util.*; public class Abstract_Set_Demo { public static void main(String[] args) { // Creating an empty AbstractSet AbstractSet<Integer> abs_set = new TreeSet<Integer>(); // Adding elements into the set abs_set.add( 15 ); abs_set.add( 20 ); abs_set.add( 30 ); abs_set.add( 40 ); abs_set.add( 50 ); // Displaying the AbstractSet System.out.println( "Initial Set is: " + abs_set); // Getting the hashcode value for the set System.out.println( "The hashcode value of the set: " + abs_set.hashCode()); } } |
Initial Set is: [15, 20, 30, 40, 50] The hashcode value of the set: 155
Note: The same operation can be performed with any type of Set with variation and combination of different data types.
Please Login to comment...