1
四處看看,無法找到/理解如何比較數組中的對象。在我下面提供的代碼中,我將如何比較數組中的對象,特別是基於兩者的成本?然後對Array進行排序,以便降低成本?如何比較和排序數組中的對象
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));
}
}
請確保所有變量名都以小寫字母開頭。即'ComputerArray'應該是'computerArray' – CubeJockey
[Java比較自定義對象]的可能的重複(http://stackoverflow.com/questions/5807704/java-comparing-custom-objects) – azurefrog