为什么compareTo()方法会在排序时导致合同违规?

Mat*_*ias 1 java

我有一个文件名列表,并希望按以下顺序进行比较:

  • 所有以".rar"结尾的名字都应该出现带有".r01",".r02"的文件之前,......
  • 所有以".par2"结尾的名称都应该出现带有任何其他后缀的文件之后

所以我在compareTo我的一个Java类中使用以下方法:

public class DownloadFile implements Comparable<DownloadFile>
{
    // custom code ...

    @Override
    public int compareTo(DownloadFile other)
    {
        if(other == null)
            throw new NullPointerException("Object other must not be null");

        // special cases -- .rar vs .par2 etc.
        String thisStr = filename.toLowerCase();
        String oStr = other.getFilename().toLowerCase();
        if(thisStr.endsWith(".rar") && oStr.matches(".*\\.r[0-9]{2,}$"))
            return -1;
        if(thisStr.matches(".*\\.r[0-9]{2,}$") && oStr.endsWith(".rar"))
            return 1;
        if(!thisStr.endsWith(".par2") && oStr.endsWith(".par2"))
            return -1;
        if(thisStr.endsWith(".par2") && !oStr.endsWith(".par2"))
            return 1;

        // normal comparison based on filename strings
        return thisStr.compareTo(oStr);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在某些数据上,这会导致以下执行:

Exception in thread "Thread-12" java.lang.IllegalArgumentException: Comparison method violates its general contract!
Run Code Online (Sandbox Code Playgroud)

我试着理解我在这里缺少什么,但我找不到问题.
你能发现我违反合同的地方吗?

PS:如果我注释掉了第二个ifs,那么仍然会抛出异常.所以问题在于前两个问题if.

Grz*_*icz 5

它不是传递性的.
元素的线性排序是不可能的.

通过反例证明.

假设你有3 DownloadFile秒(c,b,a)与小写名称:

c.par2
b.notpar2
a.par2
Run Code Online (Sandbox Code Playgroud)

为简化起见,我将使用<小写的线性排序和名称.

c.par2 < b.notpar2而且b.notpar2 < a.par2,但事实并非如此c.par2 < a.par2.
这种关系不具有传递性.

在逻辑上......它会像:

cRb而且bRa,但事实并非如此cRa.

您所要做的就是回答如何线性订购文件......
我会这样做:

if(aMethodOnThis < aMethodOnOther) {
    return -1; //or 1
}
if(aCompletelyDifferentCriterium) {
    //...
}
return 0; //or return thisFileName.compareTo(otherFileName);
Run Code Online (Sandbox Code Playgroud)

return 0在年底是非常重要的,因为它返回无法区分的文件.

在这种情况下:

public class DownloadFile implements Comparable<DownloadFile>{

    String filename;

    DownloadFile(String filename) {
        this.filename = filename;
    }

    public String getFilename() {
        return this.filename;
    }

    @Override
    public String toString() {
        return this.getFilename();
    }

    @Override
    public int compareTo(DownloadFile downloadFile) {
        String thisStr = this.filename.toLowerCase();
        String oStr = downloadFile.getFilename().toLowerCase();
        if(thisStr.endsWith(".rar")) {
            if(!oStr.endsWith(".rar"))
                return -1;
        }
        if(oStr.endsWith(".rar")) {
            if(!thisStr.endsWith(".rar"))
                return 1;
        }
        if(thisStr.matches(".*\\.r[0-9]{2,}$")) {
            if(!oStr.matches(".*\\.r[0-9]{2,}$"))
                return -1;
        }
        if(oStr.matches(".*\\.r[0-9]{2,}$")) {
            if(!thisStr.matches(".*\\.r[0-9]{2,}$"))
                return 1;
        }
        if(thisStr.endsWith(".par2")) {
            if(!oStr.endsWith(".par2"))
                return -1;
        }
        if(oStr.endsWith(".par2")) {
            if(!thisStr.endsWith(".par2"))
                return 1;
        }
        return thisStr.compareTo(oStr);
    }

    public static void main(String[] args) {
        List<DownloadFile> fileList = new ArrayList<>();
        fileList.add(new DownloadFile("a.rar"));
        fileList.add(new DownloadFile("b.rar"));
        fileList.add(new DownloadFile("a.r01"));
        fileList.add(new DownloadFile("b.r01"));
        fileList.add(new DownloadFile("a.r10"));
        fileList.add(new DownloadFile("b.r10"));
        fileList.add(new DownloadFile("a.par2"));
        fileList.add(new DownloadFile("b.par2"));
        fileList.add(new DownloadFile("a.other"));
        fileList.add(new DownloadFile("b.other"));
        Collections.shuffle(fileList);
        Collections.sort(fileList);
        System.out.println(fileList);
    }
}
Run Code Online (Sandbox Code Playgroud)

Predicate<String>从Java 8开始缩短它就派上用场了;)

@Override
public int compareTo(DownloadFile downloadFile) {
    String thisStr = this.filename.toLowerCase();
    String oStr = downloadFile.getFilename().toLowerCase();
    List<Predicate<String>> conditionList = new ArrayList<>();
    conditionList.add(s -> s.endsWith(".rar"));
    conditionList.add(s -> s.matches(".*\\.r[0-9]{2,}$"));
    conditionList.add(s -> s.endsWith(".par2"));
    for(Predicate<String> condition : conditionList) {
        int orderForCondition =
                conditionHelper(thisStr, oStr, condition);
        if(orderForCondition != 0)
            return orderForCondition;
    }
    return thisStr.compareTo(oStr);
}

private int conditionHelper(String firstStr, String secondStr,
                            Predicate<String> condition) {
    if(condition.test(firstStr))
        if(!condition.test(secondStr))
            return -1;
    if(condition.test(secondStr))
        if(!condition.test(firstStr))
            return 1;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)