package commonmethods.overridinghashcode;

/**
 * Author: Brian Dang
 * Date:   1/31/2016
 * Time:   3:41 PM
 */

/**
 * If a class is immutable and the cost of computing the hash code is significant, you might consider
 * caching the hash code in the object rather than recalculating it each time it is requested.
 *
 * If you believe that most objects of this type will be used as hash keys, then you should calculate the hash
 * code when the instance is created.
 */
public class CachedHashcode {
    private int a;
    private int b;
    private int c;

    private volatile int hashCode;  // cached hash code

    public CachedHashcode(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        CachedHashcode that = (CachedHashcode) o;

        if (a != that.a) return false;
        if (b != that.b) return false;
        if (c != that.c) return false;
        return hashCode == that.hashCode;

    }

    @Override
    public int hashCode() {
        int result = hashCode;      // cached hash code

        if(result == 0) {
            result = 17;
            result = 31 * result + a;
            result = 31 * result + b;
            result = 31 * result + c;
            hashCode = result;
        }

        return result;
    }
}
