Java File equality and ordering
Compare abstract pathnames and use them as map or set keys.
A simple example
File equality and ordering
- Start with Two paths both spelled a.txt
- Do this Compare the path values
- Result Equal
Syntax
public int compareTo(File pathname)
JDK 21 declarations (3)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaDeduplicate receipt names before a download
A purchasing team receives the same invoice name from two forms. Use the pathname objects as keys while the files are still offline and verify why the duplicate occupies one set entry.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
File a = new File("receipts", "18.txt");
File b = new File(new File("receipts"), "18.txt");
System.out.println(a.compareTo(b));
System.out.println(a.equals(b));
System.out.println(a.hashCode() == b.hashCode());
}
}
0 true true
These two constructions yield the same abstract pathname, so ordering and equality agree.
Keep two receipts with the same basename
Two shops both issue receipt number 18 and put their copies in separate folders. A catalog keyed by full path should retain both entries even though their filenames are identical.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
File north = new File("north", "18.txt");
File south = new File("south", "18.txt");
System.out.println(north.getName().equals(south.getName()));
System.out.println(north.equals(south));
}
}
true false
The filenames agree, but the parent components distinguish the two catalog keys.
Locate a rehearsal score
The choir stores each score inside a season folder. Two labels are built with the same parent and final name. Will their normalized path values compare equal?
What to watch for
The comparison follows platform pathname rules. It does not establish that two different spellings reference the same disk entry.