воскресенье, 29 апреля 2012 г.

Пример написания hashCode и equals


public class HashCodeTest {
    boolean boolVar = true;
    byte byteVar = 123;
    short shortVar = 12345;
    char charVar = 12;
    int intVar = 1234567890;
    long longVar = 1234567890123456789L;
    float floatVar = 12345.0F;
    double doubleVar = 123456789012.8D;
    int[] arrayVar = {1,2,3,4,5,6,7};
    String objectVar = "String";
    Object nullVar = null;
    
    public static void main(String[] args) {
        HashCodeTest hct = new HashCodeTest();
        HashCodeTest hct2 = new HashCodeTest();
        System.out.format("%s%n%s", hct.hashCode(), hct.equals(hct2));
    }
    
    @Override
    public int hashCode() {
        int result = 17;
        //compute int hash-code for every field
        result = 31 * result + (boolVar?1:0);
        result = 31 * result + (int) byteVar;
        result = 31 * result + (int) shortVar;
        result = 31 * result + (int) charVar;
        result = 31 * result + intVar;
        result = 31 * result + (int) (longVar ^ (longVar >>> 32));
        result = 31 * result + Float.floatToIntBits(floatVar);
        result = 31 * result + (int) (Double.doubleToLongBits(doubleVar) ^ 
            (Double.doubleToLongBits(doubleVar) >>> 32));
        result = 31 * result + 0; //for nullVar
        result = 31 * result + objectVar.hashCode();
        result = 31 * result + Arrays.hashCode(arrayVar);
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj instanceof HashCodeTest) {
            HashCodeTest hct = (HashCodeTest) obj;
            return boolVar == hct.boolVar && 
                   byteVar == hct.byteVar && 
                   shortVar == hct.shortVar && 
                   charVar == hct.charVar && 
                   intVar == hct.intVar && 
                   longVar == hct.longVar && 
                   floatVar ==  hct.floatVar && 
                   doubleVar == hct.doubleVar && 
                   Arrays.equals(arrayVar, hct.arrayVar) && 
                   objectVar.equals(hct.objectVar);
        }
        return false;
    }
}

/**
 * Output: 
 * -1172080207
 * true
 */