【问题标题】:Sort couple array [duplicate]排序夫妇数组[重复]
【发布时间】:2018-12-20 22:02:08
【问题描述】:

我有一个“Couple”类,没有什么比 String 和 double 更特别的了:

public class Couple{

public String mot;
public double indice;

public Couple(){
    this.mot = "";
    this.indice = 0;
}

public Couple(String t, double q){
    this.mot = t;
    this.indice = q;
}
}

现在,假设我有一个 Couple 数组。 我想按每个值的双精度对该数组进行排序。 例如:

排序前:

{("hi",3), ("hello",1),("Good",2),("nice",0)}

按照每对的double值排序后:

{("nice",0),("hello",1),("Good",2),("hi",3)}

【问题讨论】:

  • 有多种方法。您尝试过什么?你做了什么研究?

标签: java arrays sorting


【解决方案1】:

implements Comparable 用于情侣类,覆盖compareTo,然后使用Collections.sort(); 进行排序

public class Couple implements Comparable<Couple>{

public String mot;
public double indice;

public Couple(){
    this.mot = "";
    this.indice = 0;
}

public Couple(String t, double q){
    this.mot = t;
    this.indice = q;
}

public int compareTo(Couple obj)
{
    return (int)(indice);
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-22
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    相关资源
    最近更新 更多