我发现 Comparison 方法违反了其使用此 compareTo 方法的一般契约(Contract)异常,但我无法查明到底是什么导致了这个问题。我正在尝试以特定方式按扩展名对文件进行排序。请注意,并非所有手机都会出现这种情况,只有那些我无法访问的手机才更难测试。
public int compareTo(NzbFile another)
{
if (this.getFileName() != null && another.getFileName() != null)
{
if (this.getFileName().toLowerCase().endsWith(".nfo"))
return -1000;
else if (another.getFileName().toLowerCase().endsWith(".nfo"))
return 1000;
else if (this.getFileName().toLowerCase().endsWith(".sfv"))
return -999;
else if (another.getFileName().toLowerCase().endsWith(".sfv"))
return 1001;
else if (this.getFileName().toLowerCase().endsWith(".srr"))
return -998;
else if (another.getFileName().toLowerCase().endsWith(".srr"))
return 1002;
else if (this.getFileName().toLowerCase().endsWith(".nzb"))
return -997;
else if (another.getFileName().toLowerCase().endsWith(".nzb"))
return 1003;
else if (this.getFileName().toLowerCase().endsWith(".srt"))
return -996;
else if (another.getFileName().toLowerCase().endsWith(".srt"))
return 1004;
else
return this.getFileName().compareTo(another.getFileName());
}
else if (this.getFileName() != null && another.getFileName() == null)
{
return -995;
}
else if (this.getFileName() == null && another.getFileName() != null)
{
return 1005;
}
else
{
return this.getSubject().compareTo(another.getSubject());
}
}
最佳答案
如果您的文件名相同,并且两者都例如以 .nfo
结尾,然后这将返回它们不相等。我认为它们应该是平等的。
我强烈怀疑有更好的方法来做到这一点。我将使用 Guava对于我的示例,但这并不是绝对必要的。
static final List<String> EXTENSIONS = ImmutableList.of("nfo", "sfv", "srr", "nzb", "srt");
final Ordering<String> fileNameOrdering = new Ordering<String>() {
public int compare(String a, String b) {
String extA = Files.getFileExtension(a);
String extB = Files.getFileExtension(b);
int extAIndex = EXTENSIONS.indexOf(extA);
int extBIndex = EXTENSIONS.indexOf(extB);
if ((extAIndex >= 0) == (extBIndex >= 0)) { // if they are both known extensions or both unknown
return extAIndex - extBIndex;
} else if (extAIndex < 0) { // a is unknown, b is known
return -1;
} else if (extBIndex < 0) { // b is unknown, a is known
return 1;
}
return a.compareTo(b);
}
}.nullsLast();
return new Ordering<NzbFile>() {
public int compare(NzbFile a, NzbFile b) {
return ComparisonChain.start()
.compare(a.getFileName(), b.getFileName(), fileNameOrdering)
.compare(a.getSubject(), b.getSubject())
.result();
}
};
关于java - 比较方法违反其一般契约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9089364/