2015-09-30 76 views
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)); 
} 

}

+0

請確保所有變量名都以小寫字母開頭。即'ComputerArray'應該是'computerArray' – CubeJockey

+0

[Java比較自定義對象]的可能的重複(http://stackoverflow.com/questions/5807704/java-comparing-custom-objects) – azurefrog

回答

2

你剛纔創建的是定製比較和用戶Array的排序方法。

比較:

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

Arrays.sort(computerArray , costComparator); 

請更改您的變量名。變量名稱以小寫字母開頭。

+0

好吧謝謝生病給它一去,和生病請務必更改我的實例變量 – Consultion