Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a double value of an object within an arrayList

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

like image 801
Melo1991 Avatar asked Nov 17 '12 19:11

Melo1991


People also ask

How do you sort a double in Java?

The java. util. Arrays. sort(double[]) method sorts the specified array of doubles into ascending numerical order.

How can you sort an ArrayList of objects?

Collections. An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.

How do you sort elements in an ArrayList using comparable interface?

We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.

How do you sort a double list?

You can use sort(List<T> list) method. It will sort the double list in ascending order. If you want to sort it in descending order, you can use sort(List<T> list, Comparator<? super T> c) .


1 Answers

To use a Comparator:

Collections.sort(myList, new Comparator<Chromosome>() {     @Override     public int compare(Chromosome c1, Chromosome c2) {         return Double.compare(c1.getScore(), c2.getScore());     } }); 

If you plan on sorting numerous Lists in this way I would suggest having Chromosome implement the Comparable interface (in which case you could simply call Collections.sort(myList), without the need of specifying an explicit Comparator).

like image 143
arshajii Avatar answered Sep 21 '22 04:09

arshajii