Alex Rivera | Logout

Sorting a double value of an object within an arrayList

Asked 2012-11-17T19:43:32.270
30

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 use a comparator but I've read so many differing opinions online in the last hour that I'm utterly confused.

Attached is my code, if someone could point me in the right direction I would be much appreciated.

public class Chromosome
{

    public Gene[] genes;
    public double score;

    public Chromosome(int l)
    {
        genes = new Gene[l]; 
    }

    public int getLength()
    {
        return genes.length;
    }

    public void printChromo()
    {
        for(int i=0;i<this.genes.length;i++)
        {
            System.out.println(""+this.genes[i].teacher+","+
                this.genes[i].lecture+","+
                this.genes[i].room+","+
                this.genes[i].time+"");
        }   
    }

    public void setScore(double score)
    {
        this.score=score;
    }

    public double getScore()
    {
        return this.score;
    }
}

Don't know this make a difference but the score can only be a double between and including 0.0 to 1.0

Edit
Report

1 Answer

3

Why not use a PriorityQueue with a Comparator like this:

// your code
PriorityQueue<Chromosome> entries = new PriorityQueue<Chromosome>(1, new Comparator<Chromosome> () {
    @Override
    public int compare(Chromosome arg0, Chromosome arg1) {
        return (Double)(arg1.getScore()).compareTo((Double)arg0.getScore());
    }
});
entries.addAll(arrayListOfChromosomes);
// your code

The priority queue will then keep your data structure in sorted order.

answered 2012-11-17T19:50:23.327

Your Answer