Closed. This question is not reproducible or was caused by typos。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                    
                
        

基本上,我有两个比较器(Comparator1和Comparator2),实现方式略有不同。两者都应按行名长度的降序对列表进行排序。

Comparator2似乎不适用于java7 / java8。比较器1始终工作。
两者都适用于Java 1.6实现或如果我设置-Djava.util.Arrays.useLegacyMergeSort = true。
如果Comparator2中存在问题,则Java应该抛出IllegalArgumentException,但不会引发任何异常。

这在Java文档中表示为
“已替换了java.util.Arrays.sort和java.util.Collections.sort(间接)使用的排序算法。如果新的sort实现检测到Comparable违反Comparable合同,则它可能引发IllegalArgumentException。”

这是JRE中的错误,还是Comparator2有问题?

public class Main {

public static void main(String[] args) {
    Row row1 = new Row("AAAA");
    Row row2 = new Row("BBB");
    Row row3 = new Row("CC");
    Row row4 = new Row("D");

    List<Row> list1 = new ArrayList<Row>();
    list1.add(row2);
    list1.add(row3);
    list1.add(row1);
    list1.add(row4);

    System.out.println("Before sorting:");
    System.out.println("");

    print(list1);

    Collections.sort(list1, new Comparator2());

    System.out.println("After sorting with comparator2:");
    System.out.println("");

    print(list1);

    Collections.sort(list1, new Comparator1());

    System.out.println("After sorting with comparator1:");
    System.out.println("");

    print(list1);

}

private static void print(List<Row> list) {
    for (Row row : list) {
        System.out.println(row.name);
    }
}

}

public class Row {

String name;

public Row(String name) {
    this.name = name;
}

public int getLength() {
    return name.length();
}

}

public class Comparator1 implements Comparator<Row> {
@Override
public int compare(Row o1, Row o2) {
    Integer length1 = o1.getLength();
    Integer length2 = o2.getLength();
    return -1 * length1.compareTo(length2);
}
}

public class Comparator2 implements Comparator<Row> {

@Override
public int compare(Row o1, Row o2) {
    int length1 = o1.getLength();
    int length2 = o2.getLength();

    if (length1 < length2) {
        return 1;
    } else if (length2 > length1) {
        return -1;
    } else {
        return 0;
    }

}

}

最佳答案

Comparator2中的前两个条件基本相同:

if (length1 < length2) {
    return 1;
} else if (length2 > length1) {
    return -1;
}


else if更改为length1 > length2,它应该可以工作。

07-26 03:02