为什么Java类应实现可比性?
为什么Comparable
使用Java ?为什么有人Comparable
在课堂上实施?你需要实现可比性的真实示例是什么?
回答:
这是一个真实的例子。请注意,它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);
}
以上是 为什么Java类应实现可比性? 的全部内容, 来源链接: utcz.com/qa/402603.html