gpt4 book ai didi

java - 这个比较器类如何工作?

转载 作者:行者123 更新时间:2023-12-01 22:06:09 25 4
gpt4 key购买 nike

我在此站点中找到了这个比较器类。

Hibernate - SortedSet Mappings

但是我不明白它是如何工作的..有什么想法吗??

import java.util.Comparator;

public class MyClass implements Comparator<Certificate>{
public int compare(Certificate o1, Certificate o2) {
final int BEFORE = -1;
final int AFTER = 1;

/* To reverse the sorting order, multiple by -1 */
if (o2 == null) {
return BEFORE * -1;
}

Comparable thisCertificate = o1.getName();
Comparable thatCertificate = o2.getName();

if(thisCertificate == null) {
return AFTER * 1;
} else if(thatCertificate == null) {
return BEFORE * -1;
} else {
return thisCertificate.compareTo(thatCertificate) * -1;
}
}
}

最佳答案

这个比较器根本不起作用,因为它违反了最基本的 rules比较器如何工作。

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y

如果 xy

Comparator.compare(x , y) == -Comparator.compare(y,x) 无效> 使用 MyClass 时为 null

(This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

情况o1 == null根本没有被处理,因此会抛出异常,而情况o2 == null则不会。

这与工作比较器的样子相去甚远,最多可以被视为非常丑陋的黑客。此比较器仅适用于非null的值。在这种情况下,这只是自然顺序的相反。

关于java - 这个比较器类如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32737725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com