gpt4 book ai didi

java - 如何对数组中的对象进行比较和排序

转载 作者:行者123 更新时间:2023-11-30 03:14:58 25 4
gpt4 key购买 nike

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

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));
}

}

最佳答案

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

比较器:

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

Arrays.sort(computerArray , costComparator);

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

关于java - 如何对数组中的对象进行比较和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32872897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com