package equals_hashcode;
import java.util.Objects;
enum TransmissionType {
MANUAL,
AUTOMATIC
}
public class Car {
private String registration;
private String model;
private int odometer;
private TransmissionType transmission;
/**
* Initialises a car.
* @param registration the car's registration. i.e. number plate
* @param model the car's model
* @param odometer the car's current odometer reading
* @param transmission the car's transmission type
* */
public Car(String registration, String model, int odometer,
TransmissionType transmission) {
this.registration = registration;
this.model = model;
this.odometer = odometer;
this.transmission = transmission;
}
/**
* Returns true IF AND ONLY IF this car is equal to the other given car.
* For two cars to be equal, they must:
* have the same registration string
* have the same model string
* have the same odometer reading
* have the same transmission type
* @param obj other object to compare equality
* @return true if equal, false otherwise
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof Car) {
Car car = (Car) obj;
return registration.equals(car.registration) && model.equals(car.model) && (odometer == car.odometer) && (transmission == car.transmission);
}
return false;
}
/**
* Returns the hash code of this car.
* Two cars that are equal according to
* Car.equals(Object) should have the same hash code.
* @return hash code of this car
*/
@Override
public int hashCode() {
return Objects.hash(registration, model, odometer, transmission);
}
}
#How to override equals and hashcode methods?
9 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @late needle! Please use
/closeor theClose Postbutton above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.