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;


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();


  int hc2 = file2.hashCode();


  int hc3 = file3.hashCode();




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.
Notify of

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

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
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