Wednesday, May 10, 2006

HashCode() and Equals()

/** This code tries to explain the why it is necessary to carefully examine changes to equals() and hashCode() methods of an object. The equals method of an object should be: - Reflexive. - Symmetric. - Transitive. - consistent with the hashcode. */ import java.util.*; public class HashEqualsDemonstration { public static void main(String[] args) { HashMap h = new HashMap(); Arbitrary A = new Arbitrary(1); Arbitrary B = new Arbitrary(1); h.put(A,new String("Sample value for key value = 1")); System.out.println(h.get(B)); //since our key to hashmap is a mutable type we can change the value //but since our hashmap is not based on the state //we will get erroneous result. A.setValue(2); //this should be null since A has changed System.out.println(h.get(A)); //hence hashmap should be based on the state of the object //in case of a mutable type. } } class Arbitrary { int value; public Arbitrary() { value = -1; } public Arbitrary(int val) { value = val; } public int getValue() { return value; } public void setValue(int i) { value = i; } public boolean equals(Object o) { if(this == o) return true; if(!(o instanceof Arbitrary)) return false; Arbitrary temp = (Arbitrary) o; return (value == temp.getValue()); } public int hashCode() { return super.hashCode(); } };

0 Comments:

Post a Comment

<< Home