使用 Collection.sort 时,我不断遇到绑定(bind)不匹配问题,我不知道如何开始解决此问题。调用它的方法是这样的:
static LinkedList <Car> CarList = new LinkedList<Car>(); //Loaded LinkedList
public void DisplayAlphabetical() {
Collections.sort(CarList);
} //End of Method DisplayAlphabetical
LinkedList 使用另一个类中的 Car 参数创建一个要排序的汽车列表:
public class Car {
private String Model = "";
private String Colour = "";
private int Year = 0;
private int VIN = 0;
private double Price = 0;
static int TotalCars;
//Car Constructor
public Car (String Model, String Colour, int newYear, int newVIN, double newPrice){
this.Model = Model;
this.Colour = Colour;
this.Year = newYear;
this.VIN = newVIN;
this.Price = newPrice;
TotalCars++;
} //End of Constructor Car
//Get the car's model
public String getModel() {
return Model;
} //End of Method getModel
//Get the car's colour
public String getColour() {
return Colour;
} //End of Method getColour
//Get the year of the car
public int getYear() {
return Year;
} //End of Method getYear
//Get the VIN of the car
public int getVIN() {//static Car C = new Car(Model, Colour, Year, VIN, Price);
return VIN;
} //End of Method getVIN
//Get the price of the car
public double getPrice() {
return Price;
} //End of Method getPrice
我知道 Collection.sort 需要一个可比较的对象,但我无法弄清楚如何正确实现它。任何帮助将不胜感激。
最佳答案
我通常更喜欢使用 Comparator 与 Collections.sort(List,Comparator)而不是实现 Comparable:
public class ComparatorTest {
public static class Car {
private String model;
public Car(String model) {
this.model = model;
}
public String getModel() {
return model;
}
}
public static void main(String[] args) {
LinkedList<Car> list = new LinkedList<Car>();
list.add(new Car("Golf"));
list.add(new Car("Fiesta"));
Collections.sort(list, new Comparator<Car>() {
public int compare(Car o1, Car o2) {
String car1Model = o1.getModel();
String car2Model = o2.getModel();
// TODO! return a value!
// Read http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html#compare(T,%20T) for more information about what to return
}
});
}
}
关于java - Collection.sort 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19962046/