java - "same ordering"对象相等的重要性是什么?

标签 java sorting comparator

我正在对对象数组进行排序。这些对象有很多字段,但我只关心其中之一。所以,我写了一个比较器:

    Collections.sort(details, new Comparator<MyObj>() {
        @Override
        public int compare(MyObj d1, MyObj d2) {
            if (d1.getDate() == null && d2.getDate() == null) {
                return 0;
            } else if (d1.getDate() == null) {
                return -1;
            } else if (d2.getDate() == null) {
                return 1;
            }

            if (d1.getDate().before(d2.getDate())) return 1;
            else if (d1.getDate().after(d2.getDate())) return -1;
            else return 0;
        }
    });

从我的用例的角度来看,这个Comparator 完成了它需要做的一切,即使我可能认为这种排序是不确定的。但是,我想知道这是否是错误的代码。通过这个Comparator,两个非常不同的对象可以被认为是“相同”的排序,即使它们是不相等的对象。我决定使用 hashCode 作为决胜局,结果如下:

    Collections.sort(details, new Comparator<MyObj>() {
        @Override
        public int compare(MyObj d1, MyObj d2) {

            if (d1.getDate() == null && d2.getDate() == null) {
                return d1.hashCode();
            } else if (d1.getDate() == null) {
                return -1;
            } else if (d2.getDate() == null) {
                return 1;
            }

            if (d1.getDate().before(d2.getDate())) return 1;
            else if (d1.getDate().after(d2.getDate())) return -1;
            else return d1.hashCode() - d2.hashCode();
        }
    });

(我返回的内容可能是倒退的,但这对这个问题并不重要)

有这个必要吗?

编辑: 对于其他看到这个问题的人,请考虑使用 Google 的订购 API。上面的逻辑被替换为:

 return Ordering.<Date> natural().reverse().nullsLast().compare(d1.getDate(), d2.getDate());

最佳答案

Through this comparator, two very distinct objects could be considered "the same" ordering even if they are unequal objects.

这真的不重要;将两个对象比较为相等是完全可以的,即使它们在任何其他意义上都不“相等”。 Collections.sort 是一种稳定排序,这意味着比较相等的对象按照它们进入的顺序出现;这相当于仅使用“输入中的索引”作为决胜局。

(此外,您的新Comparator实际上比原来的更糟糕。return d1.hashCode()特别荒谬,并且return d1.hashCode () - d2.hashCode() 可能会导致不可传递的排序,由于溢出问题,会破坏 Collections.sort。除非两个整数都绝对是非负数,但 hashCode 始终不是使用 Integer.compare 比较整数。)

关于java - "same ordering"对象相等的重要性是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32257334/

相关文章:

java - 从java中的Map列表中删除值

python - 合并排序实现缓慢,怎么了?

ruby - 在 ruby​​ 中合并两个排序列表的内置方法

java - 末尾带有 null 的集合比较器

java - 如何简化多个字段上空安全比较器的创建?

java - 为什么我无法在创建实例或抛出异常时调用 initCause()

java - Gson : deserialize time serialized by Jackson

java - mysql和java jdbc从另一个类调用[运行时应用程序]

sorting - 如何按自定义顺序对列表排序?

java - 为什么通过将其大小写更改为大写然后再更改为小写来比较同一个字符两次?