class

Comparing File objects using hashcode example

This is an example of how to compare File objects using the hashcode. Each class in Java inherits hashCode() method from Object class. Comparing File objects using the hashcode implies that you should:

  • Create a few new File instances, by converting the given pathname strings into abstract pathnames. 
  • For each one of the files, use hashCode() API method of File. The method computes a hash code for each abstract pathname. Because equality of abstract pathnames is inherently system-dependent, so is the computation of their hash codes.

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

package methodoverloading;

import java.io.File;

public class Main {

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

  

  File file1 = new File("f1");

  File file2 = new File("f2");

  File file3 = new File("f3");


  int hc1 = file1.hashCode();

  System.out.println(hc1);

  int hc2 = file2.hashCode();

  System.out.println(hc2);

  int hc3 = file3.hashCode();

  System.out.println(hc3);
    }
}

Output:

-1702042073
-1185803119
-1185149680

  
This was an example of how to compare File objects using the hashcode in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
soheshdoshi
soheshdoshi
6 years ago

if my file name both are different but content same now how I compare two files with the hash code?

Back to top button