[英]Override compareTo and sort using two strings
Lets say i've a Album class. 让我们说我有一个专辑课。 How do i code the compareTo method so that when i've a ArrayList of Album object and i call
我如何编码compareTo方法,以便当我有一个Album对象的ArrayList和我调用
Collections.sort() Collections.sort()
it will sort them in by title follow by singer in ascending order. 它将按标题按照歌手按升序排序。
Public class Album implements Comparable{
private String title;
private String singer;
private double price;
.....
public int compareTo(){
// How to
}
}
I would write it like 我会这样写的
public int compareTo(Album other) {
int primary = title.compareTo(other.title);
return primary != 0 ? primary
: singer.compareTo(other.singer);
}
Personally however, I'd say it's arguable whether or not albums have a "natural ordering". 但就个人而言,我认为专辑是否具有“自然顺序”是有争议的。 Consider for instance if you, in the future, want to sort the albums on rating, or year.
例如,如果您将来想要对评级或年份的专辑进行排序,请考虑一下。
If I were you I would probably create a Comparator
for this purpose: 如果我是你,我可能会为此目的创建一个
Comparator
器:
class TitleSingerComparator implements Comparator<Album> {
public int compare(Album a, Album b) {
int primary = a.title.compareTo(b.title);
return primary != 0 ? primary
: a.singer.compareTo(b.singer);
}
}
and sort the collection using 并使用。对集合进行排序
Collections.sort(albums, new TitleSingerComparator());
public class Album implements Comparable<Album> {
...
public int compareTo(Album other) {
int cmp = title.compareTo(other.title);
if (cmp == 0) {
cmp = singer.compareTo(other.singer);
}
return cmp;
}
}
I would write it like 我会这样写的
public class Album implements Comparable<Album>{
...
public int compareTo(Album alb){
int out = this.singer.compareTo(alb.singer);
return out;
}
}
variable " out " will store either positive value( any number greater than 0) or negative value( any number less than 0) or 0 in case when Strings are equal(ie this.singer == alb.singer). 变量“ out ”将存储正值(任何大于0的数字)或负值(任何小于0的数字)或0,以防Strings相等(即this.singer == alb.singer)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.