I\'m trying to sort my custom class chromosome by the value of their score attribute which is a double. These chromosomes are stored within an ArrayList. I know I have to us
I would implement the interface Comparable:
public class Chromosome implements Comparable{
private double score;
public Chromosome(double score){
this.score = score;
}
@Override
public int compareTo(Chromosome o) {
return new Double(score).compareTo( o.score);
}
@Override
public String toString() {
return String.valueOf(score);
}
}
Note that i moved score inside the Class..
Now you can use any Collection that is Sorted (like a TreeSet)
If you insist on using the Arraylist you can use:
ArrayList out = new ArrayList();
out.add(new Chromosome(20));
out.add(new Chromosome(15));
System.out.println(out);
Collections.sort(out);
System.out.println(out);
Result:
[0.2, 0.15]
[0.15, 0.2]