3 回答

TA贡献1851条经验 获得超4个赞
String
Comparable
.
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);}

TA贡献1845条经验 获得超8个赞
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;}
public class District implements Comparable<District>{ String zipcode; Double populationDensity; public int compareTo(District other) { return populationDensity.compareTo(other.populationDensity); }}
在对象本身中,如果它是自然可比较的(扩展可比较性)。整数) 在外部比较器中提供,如上面的示例所示。

TA贡献1784条经验 获得超9个赞
此接口对实现该接口的每个类的对象强制执行总体排序。这种排序称为类的自然排序,类的比较方法称为自然比较法。 实现此接口的对象的列表(和数组)可以通过Collection s.Sort(和Arrays.Sort)自动排序。
实现此接口的对象可以用作排序映射中的键或排序集中的元素,而无需指定比较器。
添加回答
举报