排序数组列表中的一个对象的double值 [英] Sorting a double value of an object within an arrayList

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

问题描述

我试图用自己的类染色体对其分数属性的值进行排序。这些染色体存储在一个ArrayList中。我知道我必须使用比较器,但是在最后一小时内我已经读了很多不同的意见,我完全迷惑了。



附加的是我的代码,如果有人可以指出我正确的方向,我将不胜感激。

  public class染色体
{

公开基因[]基因;
公开双倍;

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之间的两倍之间

解决方案

要使用 比较器

  Collections.sort(myList,new Comparator< Chromosome>(){
@Override
public int compare(chromosome c1,染色体c2){
返回Double.compare(c1.getScore(),c2.getScore());
}
});

如果您打算排序许多列表以这种方式,我建议有染色体实现 可比较的 界面(在这种情况下,您可以简单地调用 Collections.sort(myList),而不需要指定一个明确的比较器)。


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

解决方案

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

这篇关于排序数组列表中的一个对象的double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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