这个比较器 class 是如何工作的?

How does this comparator class work?

我在这个网站上找到了这个比较器 class。

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;
      }
   }
}

有效吗?在文档中说它正在进行反向排序,

If we use sort="natural" setting then we do not need to create a separate class because Certificate class already has implemented Comparable interface and hibernate will use compareTo() method defined in Certificate class to compare certificate names. But we are using a custom comparator class MyClass in our mapping file so we would have to create this class based on our sorting algorithm. Let us do descending sorting in this class using this class.

据我所知,这似乎不太正确...除非两个证书名称都正确。

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) {       // if o2 = null > o1 goes first
     return BEFORE * -1;  // -1 * -1 = 1 so o1 goes first
  }

  Comparable thisCertificate = o1.getName();  // get o1 name to compare
  Comparable thatCertificate = o2.getName();  // get o2 name to compare

  if(thisCertificate == null) {         // if o1 name is null, o2 goes first
     return AFTER * 1;                  // 1 * 1 = 1 > o1 goes first
  } else if(thatCertificate == null) {  // if o2 name is null, o1 goes first
     return BEFORE * -1;                // -1 * -1 = 1 > o1 goes first
  } else {                              
     // if both certs names are valid compare them in the usual way 
     //  sorting inversed because of the -1.
     return thisCertificate.compareTo(thatCertificate) * -1;
  }
}

这个比较器根本不起作用,因为它违反了 Comparator 工作原理的最基本 rules

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

如果使用 MyClass.

xynull,则

Comparator.compare(x , y) == -Comparator.compare(y,x) 无效

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

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

这与工作比较器的外观相去甚远,最多可以被视为非常丑陋的 hackComparator 仅适用于非 null 的值。在那种情况下,它只是自然顺序的倒转。