我想对此Arraylist进行排序
public List<Machine> machines;
machines = machineController.execute().get();
Collections.sort(machines, new Comparator<Machine>() {
public int compare(Machine obj1, Machine obj2)
{
return obj1.getManufacturer().compareToIgnoreCase(obj2.getManufacturer());
}
});
现在,列表显示了从A到Z的制造商。工作正常。
宝马Z1,
BMX X6,
大众捷达,
大众高尔夫,
问题是:我如何按制造商排序?模型? (obj.getManufaturer&amp; obj.getModel)
宝马X6,
宝马Z1,
大众高尔夫,
大众捷达
答案 0 :(得分:4)
您需要在Machine类中覆盖“compare”以按制造商和型号进行排序。如果你现在看看它的方式,你只需要按制造商进行比较。您希望通过“机器”作为整个实体进行比较。
这应该足以解决您的问题,但如果您想要示例代码,请告诉我,我可以编辑此帖子:)
编辑:我测试的工作示例:
在您的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
答案 1 :(得分:1)
你可以这样做:
public int compare(Machine obj1, Machine obj2){
if (obj1.getManufacturer().compareToIgnoreCase(obj2.getManufacturer()) != 0) {
return obj1.getManufacturer().compareToIgnoreCase(obj2.getManufacturer());
} else {
return obj1.getModel().compareToIgnoreCase(obj2.getModel());
}
}