-1

I have a "Couple" class with nothing more special than a String and a 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;
}
}

Now, suppose I have an array of Couple. I want to sort that array by the double from each value. For example:

Before sorting :

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

After sorting according to the double values of each couple:

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

amin saffar
  • 1,953
  • 3
  • 22
  • 34
johanDa9u
  • 63
  • 5

1 Answers1

0

use implements Comparable for couple class , override compareTo and then sort with 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);
}
}
amin saffar
  • 1,953
  • 3
  • 22
  • 34