【问题标题】:Sort with 2 conditions in java strictly using compareTo [duplicate]严格使用compareTo在java中使用2个条件进行排序[重复]
【发布时间】:2020-02-14 10:34:27
【问题描述】:
    public int compareTo(T o){

      if (this.getId().charAt(0) < o.getId() ){
         return 1;
      }else{
         return -1;
      }

      //Id data = a, b, f, z
      //num data = 1, 2, 4, 8

      //i want to sort the list according to their id first. then also sort it with their 'num' after sorting with their id first
         //sort id first. sort according to num after
   }

}

我想先根据他们的 id 对列表进行排序。然后根据num。我会怎样..

【问题讨论】:

标签: java sorting compareto


【解决方案1】:

尝试以下 sn-p。

public int compareTo(Person o){

    int idResult=id.compareTo(o.getId();
    if (idResult == 0) {//same
        return Integer.compare(this.num, o.num);//compare numbers
    }
    return idResult;//else return resut of id comparison
}

【讨论】:

  • 不要对字符串执行两次compareTo()。不要使用减号运算符比较整数。
猜你喜欢
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多