的ArrayList中排序对象的双重价值 [英] Sorting a double value of an object within an arrayList

查看:96
本文介绍了的ArrayList中排序对象的双重价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过自己的得分属性的值,它是一个双排序我的自定义类染色体。这些染色体存储一个ArrayList中。我知道我必须使用一个比较,但我在网上看了这么多不同的观点我最后HR说我心乱如麻。

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 i the last hr that I'm utterly confused.

Attachedis我的code,如果some1能在正确的方向指向我这将是更AP preciated。

Attachedis my code,if some1 could point me in the right direction it 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;
    }
}

不知道这个有所作为,但成绩只能是双之间,包括0.0和1.0

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

推荐答案

要使用<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html\"><$c$c>Comparator:

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

如果你打算用这种方式,我建议有无数的排序列表取值染色体实施<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html\"><$c$c>Comparable接口(在这种情况下,你可以简单的叫 Col​​lections.sort(myList中),而不需要指定一个明确的比较 )。

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).

这篇关于的ArrayList中排序对象的双重价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆