3 回答
TA貢獻1851條經驗 獲得超4個贊
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);}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)自動排序。
實現此接口的對象可以用作排序映射中的鍵或排序集中的元素,而無需指定比較器。
添加回答
舉報
