You would need to override "compare" in your Machine class to sort by both the Manufacturer and model. If you look at the way you have it now, you are simply comparing by Manufacturer. You want to compare by "Machine" as a whole entity.
That should be enough to solve your problem, but if you would like example code let me know and I can edit this post :)
EDIT: working example that I tested:
Inside of your Machine class use:
public class Machine implements Comparable<Machine>
Then, you need:
@Override
public int compareTo(Machine o) {
if (manufacturer.compareToIgnoreCase(o.manufacturer) == 0)
return model.compareToIgnoreCase(o.model);
else
return manufacturer.compareToIgnoreCase(o.manufacturer);
}
and then, you can simply call:
Collections.sort(machines);
Happy coding!
Here is the exact code I personally used for testing:
public class Machine implements Comparable<Machine> {
private String manufacturer;
private String model;
private double price;
public Machine(String man, String mod) {
this(man, mod, 0);
}
public Machine(String man, String mod, double p) {
manufacturer = man;
model = mod;
price = p;
}
/**
* @return the manufacturer
*/
public String getManufacturer() {
return manufacturer;
}
/**
* @return the model
*/
public String getModel() {
return model;
}
public double getPrice() {
return price;
}
@Override
public int compareTo(Machine o) {
if (manufacturer.compareToIgnoreCase(o.manufacturer) == 0)
return model.compareToIgnoreCase(o.model);
else
return manufacturer.compareToIgnoreCase(o.manufacturer);
}
@Override
public String toString() {
return manufacturer.toString() + " " + model.toString();
}
}
and
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Blah {
public static void main(String[] args) {
List<Machine> machines = new ArrayList<>();
machines.add(new Machine("Volkswagen", "Jetta"));
machines.add(new Machine("Volkswagen", "Golf"));
machines.add(new Machine("BMW", "Z1"));
machines.add(new Machine("BMW", "X6"));
Collections.sort(machines);
for (Machine m : machines)
System.out.println(m.toString());
}
}
For me, this outputs:
BMW X6
BMW Z1
Volkswagen Golf
Volkswagen Jetta