如何比较和排序数组中的对象

时间:2015-09-30 18:06:46

标签: java arrays sorting

环顾四周,找不到/理解数组中对象的比较是如何工作的。在下面提供的代码中,我如何能够根据两者的成本比较数组中的对象?然后对数组进行排序,使成本按降序排列?

public class PC
{
private int VRAM;
public String Processor;
public int RAM;
public int Harddrive;
public double Cost;


 public Desktop(String Proc, int ram, int HD, int Vram)   
{
      Processor = Proc;
      RAM = ram;
      Harddrive = HD;
      VRAM = Vram ;    

}

public double getCost()
{
     Cost = 250 + (5.50*RAM) + (0.10*Harddrive) + (0.30*VRAM);
     return Cost;

}
public String toString()
{        
    return "Desktop\n" + "--------\n" + "CPU: " + Processor + "\nRAM: " + RAM + "GB\n" + "HDD: " + Harddrive + "GB\n" + "VRAM: " + VRAM + "MB" + "\nCost: $" + Cost + "\n";
}

}

public class Main 
{
public static void main(String[] args)//Main method has been tested throughly, but the output seems to get a bit nasty
{     
    Computer[] ComputerArray = new Computer[5];//when to many are called all out once.
    ComputerArray[0] = (new PC ("Intel Core i7 2600k", 4, 700, 1400));
    ComputerArray[1] = (new PC ("AMD FX-8150", 16, 1950, 1100));
 }

}

1 个答案:

答案 0 :(得分:2)

您只需创建一个用户比较器和用户数组的排序方法。

比较者:

show $ show something

public class CostComparator implements Comparator<Computer> {
    @Override
    public int compare(Computer o1, Computer o2) {
        return o1.getCost().compareTo(o2.getCost());
    }
}

请更改您的变量名称。变量名以小写字母开头。