System.identityHashCode() Method in Java With Examples
Last Updated :
15 Oct, 2019
The java.lang.System.identityHashCode() is the method which is used to return the same hash code for any given object that is returned by the default method hashCode(). Also, for every hash code with a null reference zero is returned.
Points to be Remembered:
- By default, every class either implicitly or explicitly provides a hashCode() method
- A hashcode is generally a number generated from any object which allows objects to be stored or retrieved very quickly in a Hashtable.
- In Java, hashCode() by default is a native method, which means that the method has a modifier ‘native’, when it is implemented directly in the native code in the JVM.
- Used to digest all the data stored in an instance of the class into a single hash value i.e., a 32-bit signed integer.
Syntax :
public static int identityHashCode(Object x)
Parameters: The parameter x is of the type of the Hash and refers to the hashCode that is needed to be calculated.
Return Value: This method returns the hashCode.
Below programs illustrate the use of java.lang.System.identityHashCode() method.
Program 1:
import java.lang.*;
import java.io.*;
public class SystemCode1 {
public static void main(String[] args) throws Exception
{
File filename1 = new File( "Welcome" );
File filename2 = new File( "Welcome" );
File filename3 = new File( "Geek" );
File filename4 = new File( "World" );
int returnvalue1 = System.identityHashCode(filename1);
System.out.println(returnvalue1);
int returnvalue2 = System.identityHashCode(filename2);
System.out.println(returnvalue2);
int returnvalue3 = System.identityHashCode(filename3);
System.out.println(returnvalue3);
int returnvalue4 = System.identityHashCode(filename4);
System.out.println(returnvalue4);
}
}
|
Output:
589431969
1252169911
2101973421
685325104
Explanation:
In the above program, different hashcode or number are generated from an object even if they have the same name. Like here we can see first two terms are same i.e., “Welcome”, but we have two different values, which are
respectively for first and second Welcome
Program 2:
import java.lang.*;
import java.io.*;
public class SystemCode2 {
public static void main(String[] args) throws Exception
{
File filename1 = new File( "10" );
File filename2 = new File( "shyam" );
File filename3 = new File( "s12" );
File filename4 = new File( "s12" );
int returnvalue1 = System.identityHashCode(filename1);
System.out.println(returnvalue1);
int returnvalue2 = System.identityHashCode(filename2);
System.out.println(returnvalue2);
int returnvalue3 = System.identityHashCode(filename3);
System.out.println(returnvalue3);
int returnvalue4 = System.identityHashCode(filename4);
System.out.println(returnvalue4);
}
}
|
Output:
589431969
1252169911
2101973421
685325104
Share your thoughts in the comments
Please Login to comment...