diff --git a/04-collections-clean-code/snippets/src/comparators/Car.java b/04-collections-clean-code/snippets/src/comparators/Car.java index 652f10fd..ce7c1a6d 100644 --- a/04-collections-clean-code/snippets/src/comparators/Car.java +++ b/04-collections-clean-code/snippets/src/comparators/Car.java @@ -1,11 +1,21 @@ package comparators; +import java.util.Objects; + public class Car implements Comparable { + 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; } @@ -18,10 +28,17 @@ 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 @@ -29,13 +46,24 @@ 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 + '\'' + + '}'; } }