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

为什么Java类应实现可比性?,第1张

为什么Java类应实现可比性

这是一个真实的例子。请注意,它

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

后来..

public List<Author> listAuthors(){    List<Author> authors = readAuthorsFromFileOrSomething();    Collections.sort(authors);    return authors;}public SortedSet<Author> listUniqueAuthors(){    List<Author> authors = readAuthorsFromFileOrSomething();    return new TreeSet<Author>(authors);}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5146076.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存