class

IdentityHashcode example

With this example we are going to demonstrate how to get the identity hashcode of a File. Each class in Java inherits hashCode() method from Object class. The identity hashCode is the hashcode that the object of the class would return. In short, to get the identity hashCode of a File you should:

  • Create a few new File instances, by converting the given pathname strings into abstract pathnames.
  • For each one of the files, use identityHashCode(Object x) API method of System. The method returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object’s class overrides hashCode().

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.io.File;

public class Main {

    public static void main(String[] argv) throws Exception {

  File file1 = new File("C:/Users/nikos7/Desktop/snippets-howto.txt");

  File file2 = new File("C:/Users/nikos7/Desktop/snippets-howto2.txt");

  File file3 = new File("C:/Users/nikos7/Desktop/snippets-howto3.txt");

  

  int ihc1 = System.identityHashCode(file1);

  System.out.println(ihc1);

  int ihc2 = System.identityHashCode(file2);

  System.out.println(ihc2);

  int ihc3 = System.identityHashCode(file3);

  System.out.println(ihc3);

    }
}

Output:

1688622944
1689424703
132202687

 
This was an example of how to get the identity hashcode of a file in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button