为什么Java类应该实现可比性?

2022-08-31 07:46:48

为什么使用Java?为什么有人会在课堂上实现?您需要实现可比较的现实生活中的示例是什么?ComparableComparable


答案 1

这是一个现实生活中的示例。请注意,还实现了 。StringComparable

class Author implements Comparable<Author>{
    String firstName;
    String lastName;

    @Override
    public int compareTo(Author other){
        // compareTo should return < 0 if this is supposed to be
        // less than other, > 0 if this is supposed to be greater than 
        // other and 0 if they are supposed to be equal
        int last = this.lastName.compareTo(other.lastName);
        return last == 0 ? this.firstName.compareTo(other.firstName) : last;
    }
}

后。。

/**
 * List the authors. Sort them by name so it will look good.
 */
public List<Author> listAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    Collections.sort(authors);
    return authors;
}

/**
 * List unique authors. Sort them by name so it will look good.
 */
public SortedSet<Author> listUniqueAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    return new TreeSet<Author>(authors);
}

答案 2

可比性定义了自然排序。这意味着,当一个对象应被视为“小于”或“大于”时,您正在定义它。

假设您有一堆整数,并且想要对它们进行排序。这很容易,只需将它们放在一个排序的集合中,对吧?

TreeSet<Integer> m = new TreeSet<Integer>(); 
m.add(1);
m.add(3);
m.add(2);
for (Integer i : m)
... // values will be sorted

但现在假设我有一些自定义对象,其中排序对我来说是有意义的,但是没有定义。比方说,我有按邮政编码和人口密度表示选区的数据,我想按密度对它们进行排序:

public class District {
  String zipcode; 
  Double populationDensity;
}

现在,对它们进行排序的最简单方法是通过实现Compeable来定义它们,这意味着有一种标准的方式来定义这些对象的排序方式:

public class District implements Comparable<District>{
  String zipcode; 
  Double populationDensity;
  public int compareTo(District other)
  {
    return populationDensity.compareTo(other.populationDensity);
  }
}

请注意,您可以通过定义比较器来执行等效操作。不同之处在于比较器在对象外部定义排序逻辑。也许在单独的过程中,我需要按邮政编码对相同的对象进行排序 - 在这种情况下,排序不一定是对象的属性,或者与对象的自然排序不同。您可以使用外部比较器来定义对整数的自定义排序,例如,按字母值对整数进行排序。

基本上,排序逻辑必须存在于某个地方。那可以是——

  • 在对象本身中,如果它自然具有可比性(扩展可比性 -例如整数)

  • 在外部比较器中提供,如上例所示。


推荐