我如何按第二个对象对此ArrayList进行排序,在本例中为“cost”?

时间:2016-03-17 02:34:11

标签: java arraylist

以下是参数:

public class SoftwareProject implements Comparable<SoftwareProject> {
    String porjectID;
    double cost;
    int duration;

    public SoftwareProject(String id, double cost, int duration)
    {
        this.porjectID = id;
        this.cost = cost;
        this.duration = duration;
    }

    @Override
    public int compareTo(SoftwareProject rhs) {
        return Double.valueOf(this.cost).compareTo(cost);
    }
}

这是主文件:

public class CaluclateArray {

    static List<SoftwareProject> list;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        initialize();

        int sum = 0;

        for (int i = 0; i < list.size(); i++) {
            sum += list.get(i).cost;

            System.out.println("Sum: " + sum + "\n");
        }

        for (int i = 0; i < list.size(); i++)
        {
            System.out.println(list.get(i).cost);
        }


        //System.out.println("Prices of top 5 most expensive: " + list.get(0).cost);
    }

    static void initialize() {
        list = new ArrayList<>();
        SoftwareProject s = new SoftwareProject("5434", 225000.0, 152);
        list.add(s);
        s = new SoftwareProject("1234", 50000.0, 52);
        list.add(s);
        s = new SoftwareProject("2234", 1000.0, 35);
        list.add(s);
        s = new SoftwareProject("2134", 10000.0, 35);
        list.add(s);
        s = new SoftwareProject("2224", 1110000.0, 35);
        list.add(s);
        s = new SoftwareProject("2244", 140000.0, 35);
        list.add(s);
        s = new SoftwareProject("2235", 30000.0, 35);
        list.add(s);
        s = new SoftwareProject("2236", 750000.0, 35);
        list.add(s);
        s = new SoftwareProject("2237", 75000.0, 35);
        list.add(s);
        s = new SoftwareProject("2254", 8000.0, 35);
        list.add(s);
        s = new SoftwareProject("2634", 80000.0, 35);
        list.add(s);
        s = new SoftwareProject("2231", 23000.0, 35);
        list.add(s);
        s = new SoftwareProject("4321", 15000.0, 35);
        list.add(s);

        Collections.sort(list);
    }
}

我想知道如何按构造函数cost中的第二个参数(SoftwareProject(String id, double cost, int duration))进行排序,我在执行此操作时遇到了困难。

Collections.sort(list);无效

1 个答案:

答案 0 :(得分:0)

您的compareTo方法中出现问题。通过将this.cost与成本进行比较,您实际上是将单个对象的成本与自身进行比较,因为this.costcost相同。 cost只是SoftwareProject类中的一个字段,但您需要访问两个不同的成本字段,而您当前只能访问一个this成本字段,这是简单的解决方案是使用方法中的参数。

@Override
    public int compareTo(SoftwareProject rhs) {
        return Double.valueOf(this.cost).compareTo(rhs.cost);//you can even switch
                                                             //this.cost with rhs.cost
                                                             //or even write cost instead of this.cost
    }