java - Collection.sort 的问题

标签 java sorting

使用 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/

相关文章:

java - quartz 作业未触发

java - Sonar 问题 - 数组直接存储

java - JScrollPane 和 printAll()

delphi - 如果列表已排序,为什么 Delphi 的 TStringList.InsertObject() 方法会抛出异常?

java - 使用比较器接口(interface)和 java 8 Streams 进行排序

Java.util.Date 空输出

java - 如何通过 solrTemplate 获取建议

javascript - 使用 for 循环的冒泡排序无法按预期工作

c++ - std::sort 中的错误?

javascript - JS用字符串和字符串数字排序数组