覆盖compareTo并使用两个字符串进行排序

时间:2012-02-16 08:21:23

标签: java

让我说我有一个专辑课。我如何编码compareTo方法,以便当我有一个Album对象的ArrayList并且我调用

Collections.sort()

它将按标题按照歌手按升序排序。

Public class Album implements Comparable{

private String title;
private String singer;
private double price;

.....

public int compareTo(){

// How to

}

}

3 个答案:

答案 0 :(得分:5)

我会像

那样写
public int compareTo(Album other) {
    int primary = title.compareTo(other.title);
    return primary != 0 ? primary
                        : singer.compareTo(other.singer);
}

然而,就个人而言,我认为专辑是否具有“自然顺序”是有争议的。例如,考虑您将来是否希望对评级或年份的专辑进行排序。

如果我是你,我可能会为此目的创建一个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);
    }
}

使用

对集合进行排序
Collections.sort(albums, new TitleSingerComparator());

答案 1 :(得分:3)

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

答案 2 :(得分:0)

我会这样写

public class Album implements Comparable<Album>{   
  ...   
  public int compareTo(Album alb){
  int out  = this.singer.compareTo(alb.singer);     
  return out;
  }
}

变量“ out ”将存储正值(大于0的任何数字)或负值(小于0的任何数字),或者在字符串相等的情况下存储0(即this.singer = = alb.singer)。