Skip to content

Commit

Permalink
Fix Comparable/Comparator code snippet
Browse files Browse the repository at this point in the history
  • Loading branch information
100yo committed Nov 2, 2024
1 parent 98ba18a commit cd4295b
Showing 1 changed file with 34 additions and 6 deletions.
40 changes: 34 additions & 6 deletions 04-collections-clean-code/snippets/src/comparators/Car.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
package comparators;

import java.util.Objects;

public class Car implements Comparable<Car> {

private final String vin; // unique identifier
private int topSpeed;
private String color;
private String brand;

public Car(String vin, int topSpeed, String color, String model) {
this.vin = vin;
this.topSpeed = topSpeed;
this.color = color;
this.brand = model;
}

public int getTopSpeed() {
return topSpeed;
}
Expand All @@ -18,24 +28,42 @@ public String getBrand() {
return brand;
}

public Car(int topSpeed, String color, String model) {
this.topSpeed = topSpeed;
this.color = color;
this.brand = model;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return Objects.equals(vin, car.vin);
}

@Override
public int hashCode() {
return Objects.hashCode(vin);
}

@Override
public int compareTo(Car other) {
// Let's sort the cars by top speed in ascending order.
// The method returns a negative integer, zero, or a positive integer when this car's top speed
// is less than, equal to, or greater than the top speed of the specified object.
// Integer.compare(other.topSpeed, this.topSpeed);

// make sure the natural ordering is consistent with equals()
if (this.vin.equals(other.vin)) {
return 0;
} else if (this.topSpeed == other.topSpeed) {
return -1; // workaround, but should not return 0 to remain consistent with equals()
}
return Integer.compare(this.topSpeed, other.topSpeed);
}

@Override
public String toString() {
return "[topSpeed=" + this.topSpeed + ", color=" + this.color + ", model=" + this.brand + "]";
return "Car{" +
"vin='" + vin + '\'' +
", topSpeed=" + topSpeed +
", color='" + color + '\'' +
", brand='" + brand + '\'' +
'}';
}

}

0 comments on commit cd4295b

Please sign in to comment.