您需要在您的机器类中覆盖“比较”以按制造商和型号进行排序。如果你看你现在拥有它的方式,你只是在按制造商进行比较。您想通过“机器”作为一个整体进行比较。
这应该足以解决您的问题,但是如果您想要示例代码,请告诉我,我可以编辑这篇文章:)
编辑:我测试的工作示例:
在您的 Machine 类内部使用:
public class Machine implements Comparable<Machine>
然后,您需要:
@Override
public int compareTo(Machine o) {
if (manufacturer.compareToIgnoreCase(o.manufacturer) == 0)
return model.compareToIgnoreCase(o.model);
else
return manufacturer.compareToIgnoreCase(o.manufacturer);
}
然后,您可以简单地调用:
Collections.sort(machines);
快乐编码!
这是我个人用于测试的确切代码:
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();
}
}
和
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());
}
}
对我来说,这输出:
BMW X6
BMW Z1
Volkswagen Golf
Volkswagen Jetta