java - How to compare and sort objects within an Array -
been around , can not find/understand how comparing objects within array works. in code provided below, how able compare objects, within array based on cost of two? sorting array cost 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, output seems bit nasty { computer[] computerarray = new computer[5];//when many called out once. computerarray[0] = (new pc ("intel core i7 2600k", 4, 700, 1400)); computerarray[1] = (new pc ("amd fx-8150", 16, 1950, 1100)); } }
you create custome comparator , 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 variable names. variable names starts lower case letters.
Comments
Post a Comment