在课程中,他们展示了这样一个示例,特别省略了 private 和 getter 和 setter:
public class Car implements Comparable<Car> {
String brand;
String model;
int year;
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
@Override
public int compareTo(Car car) {
if (this.year == car.year) {
return 0;
} else if (this.year < car.year) {
return -1;
} else {
return 1;
}
}
我可以替换这段代码吗:
@Override
public int compareTo(Car car) {
if (this.year == car.year) {
return 0;
} else if (this.year < car.year) {
return -1;
} else {
return 1;
}
对此:
@Override
public int compareTo(Car car) {
return Integer.compare(this.year, car.year);
}
你能告诉我这是否正确吗?
关于同一主题的另一个问题:
这是添加的代码,它按 YEAR(年份)正确排序,但是如何使其按所有字段排序?
public class Test {
public static void main(String[] args) {
TreeSet<Car> myCarList = new TreeSet<>();
Car firstCar = new Car("Mercedes", "E200", 2015);
Car secondCar = new Car("Bmw", "M5", 2017);
Car thirdCar = new Car("Audi", "Q8", 2020);
myCarList.add(firstCar);
myCarList.add(secondCar);
myCarList.add(thirdCar);
for (Car car: myCarList) {
System.out.println(car);
}
}
}
要按所有字段排序,我这样做了:
@Override
public int compareTo(Car car) {
if (this.brand.equals(car.brand) && this.model.equals(car.model) && this.year == car.year) {
return 0;
} else if (this.brand.equals(car.brand) && this.model.equals(car.model) && this.year < car.year) {
return -1;
} else {
return 1;
}
}
但它只按年份排序,请告诉我如何按我的示例中的所有字段排序?