Collections.sort在Java 1.7上不起作用

Aid*_*den 1 java sorting collections comparator

Java 6使用合并排序来比较Collections.sort()中的两个对象,而Java 1.7使用Timsort

我有这个课供对象排序

Class ObjectSort 
{
    String Name = "";
    int priority = 0;

    public ObjectSort (String name, int priority)
    {
        this.Name = Name;
        this.priority = priority;
    }

    public getPriority()
    {
        return priority;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试课是

TestClass 
{
     ...main()
    {
      List<ObjectSort> sorted = new ArrayList<ObjectSort> ();
      sorted.add ("Table", 99);
      sorted.add ("Chair", 1);
      Collections.sort(sorted, new Comparator ());
    }

 // inner class to define comparator logic
 private static final class Comparator implements  java.util.Comparator<ObjectSort>
 {
    @Override
    public int compare (ObjectSort f1, ObjectSort f2)
    {
        try
        {
            // Get the allocation priorities
            int priority1 = f1.getPriority ();
            int priority2 = f2.getPriority ();

            if (priority1 == priority2)
                return 0;
            else
                return (priority1 > priority2 ? 1 : 0);
        }
        catch (Exception e)
        {
            // Shouldn't happen, because we have the objects OK and there's no database activity
            // happening here.
            assert true;
        }
        return 0;
    }
}

}
Run Code Online (Sandbox Code Playgroud)

现在,当我们在java 1.6中运行代码时,它可以正确地对其进行排序,Chair出现在BEFORE表之前,这是我要的升序。

但是,如果代码在Java 1.7中运行,则根本不对代码进行排序,Table排在Chair之前。我检查了1.6使用合并排序,而1.7使用Timsort。请帮我告诉我代码有什么问题吗?

更新在1.7中,变量f1中的主席在代码执行期间出现,而在1.6中,Table出现了!

谢谢!

艾登

Pet*_*rey 5

问题是您的比较器损坏了。当你有一个比较器

comparator.compare(a, b) == -comparator.compare(b, a)
Run Code Online (Sandbox Code Playgroud)

Java 7不接受的原因是:Java 7对此条件进行了更多检查。

他们已经将Java更新为1.7 :(并且此代码现在在这里不起作用:(

它从来没有用过,以前可能没有正确排序,但是以前没有遇到运行时错误。

可以使用的较短版本是:(不要重复使用通用内置类的名称)

static class ObjectSortComparator implements Comparator<ObjectSort> {
    @Override
    public int compare (ObjectSort f1, ObjectSort f2) {
        // Get the allocation priorities
        int priority1 = f1.getPriority ();
        int priority2 = f2.getPriority ();

        return priority1 == priority2 ? 0 : (priority1 > priority2 ? 1 : -1);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:在Java 8中,您无需自己编写此代码,您可以

sorted.sort(Comparator.comparingInt(ObjectSort::getPriority));
Run Code Online (Sandbox Code Playgroud)