My application compares file names and one user got "comparison method violates its general contract java". But I cant reproduce error.
My question: Is it ok, when my @Override compare() method return 0, which means that object are equals?
This is my code:
Two types of sort: 1) by last modified date 2) by regex digit in file name.
public class FileComparator implements Comparator<File> {
int sortType;
public FileComparator(int sortType) {
this.sortType = sortType;
}
@Override
public int compare(File f1, File f2) {
int result;
try {
switch (sortType) {
case Constants.SORT_BY_DATE:
result = f1.lastModified() > f2.lastModified() ? 1 : -1;
break;
case Constants.SORT_BY_DIGID:
result = checkByDigit(f1, f2);
break;
default:
result = f1.lastModified() > f2.lastModified() ? 1 : -1;
break;
}
return result;
} catch (Exception e) {
return 0;
}
}
private static int checkByDigit(File f1, File f2) {
String regEx;
Pattern p;
Matcher m1;
Matcher m2;
try {
String f1Name = f1.getName().toUpperCase();
String f2Name = f2.getName().toUpperCase();
// "ScanImage _ 001"
regEx = "(SCANIMAGE)(\\D*)(\\d+)";
p = Pattern.compile(regEx);
m1 = p.matcher(f1Name);
m2 = p.matcher(f2Name);
if (m1.find() && m2.find()) {
return Integer.parseInt(m1.group(3)) > Integer.parseInt(m2.group(3)) ? 1 : -1;
}
// "No_digits_here_001",""No_digits_here_002"
regEx = "(\\D+)(\\d+)";
p = Pattern.compile(regEx);
m1 = p.matcher(f1Name);
m2 = p.matcher(f2Name);
if (m1.find() && m2.find()) {
return Integer.parseInt(m1.group(2)) > Integer.parseInt(m2.group(2)) ? 1 : -1;
}
// We didnt find any digit, use lexicographically compare
return f1.compareTo(f2);
} catch (Exception e) {
//
}
return 0;
}
}