brainydexter
brainydexter

Reputation: 20356

how should I invoke super.hashcode with google guava hashCode()

public abstract class HolidayPackageVariant {
private HolidayPackage holidayPackage;
private String typeHolidayPackage;

@Override
    public int hashCode() {
        return Objects.hashCode(getTypeHolidayPackage(), getHolidayPackage());
    }
}

public final class FlightHolidayPackageVariant extends HolidayPackageVariant{
private Destination originCity;

@Override
    public int hashCode() {
        // need to add super.hashCode() here somehow ?
        return Objects.hashCode(getOriginCity() );
    }
}

Google guava hashode(): Objects.hashCode works on member objects. How do I specify super class hashCode() in the derived::hashCode() ? I can directly use super.members in the derived class hashCode() function, but if the super.hashCode() changes in any way, that will not be reflected in the derived:hashCode(...).

Upvotes: 1

Views: 1707

Answers (3)

kevinarpe
kevinarpe

Reputation: 21319

Your class only has one new data member, so there is no need to use Objects.hashCode(Object...). Try this instead:

public int hashCode() {
    Destination oc = getOriginCity();
    return 31 * super.hashCode() + (null == oc ? 0 : oc.hashCode());
}

If you have many new data members in the subclass, something like this would also work:

public int hashCode() {
    return 31 * super.hashCode() + Objects.hashCode(getOriginCity(), getOtherData(), getMoreData());
}

Upvotes: 0

Kevin Bourrillion
Kevin Bourrillion

Reputation: 40851

Sorry for the non-answer but: this is probably not really what you want to do. Effective Java has a long exploration of why subclassing a value type to add an additional value component is a bad idea. In the second edition, it's Item 8, "Obey the general contract when overriding equals." Also see Item 16, "Favor composition over inheritance."

Upvotes: 8

Bohemian
Bohemian

Reputation: 425188

The hashcode is itself an (auto-boxed Integer) object, so just include super.hashCode() in the objects that make up the hash:

public int hashCode() {
    return Objects.hashCode(getOriginCity(), super.hashCode());
}

Upvotes: 5

Related Questions