2

Been look around and can not find/understand how comparing objects within an array works. In the code I provided below, how would I be able to compare the objects, within an array based specifically on the cost of the two? Then sorting the Array so the cost is in descending order?

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
  • 1
    Please be sure all variable names begin with a lower case letter. i.e. ComputerArray should be computerArray Commented Sep 30, 2015 at 18:08

1 Answer 1

3

You just create a custome comparator and user Array's sort method.

Comparator :

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

and

Arrays.sort(computerArray , costComparator);

Please change your variable names. Variable names starts with lower case letters.

Sign up to request clarification or add additional context in comments.

1 Comment

okay thanks ill give it a go, and ill be sure to change my instance variables

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.