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
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:
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.