23 February 2010

Remember, equals() and hashCode() are so important, Don't miss!

equals() and hashCode() are two important methods that you need to implement to activate the .equals() method of your own objects.

Note:
Remmeber too, "==" used only for identiy, i.e it returns true as only of the two references refer to the same object.

Special attention should be taken when using your objects as keys in a map (hashtable), because the internal implementation of Sets and Maps uses those two methods in critical usage . See the following Example :

Scenario 1 : Key.java without equals and hashCode :

 public class Key {  
private int id;
private String value;

public Key(String value, int id) {
super();
this.value = value;
this.id = id;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

 import java.util.HashMap;  
import java.util.Map;


public class Main {
public static void main(String[] args) {
Map<Key, String> map = new HashMap<Key, String>();
Key key = new Key("ABC", 1);
map.put(key, "Hello World");

//
Key sameKey = new Key("ABC", 1);
System.out.println(map.get(sameKey));
}
}

// OUTPUT : null
Scenario 2 : Key.java with equals and hashCode :
 public class Key {  
private int id;
private String value;

public Key(String value, int id) {
super();
this.value = value;
this.id = id;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}

public boolean equals(Object obj) {
if (!(obj instanceof Key)) return false;
Key other = (Key) obj;
return this.getValue().equals(other.getValue()) && getId() == other.getId();
}
public int hashCode() {
return getValue().hashCode() * getId();
}
}

 import java.util.HashMap;  
import java.util.Map;


public class Main {
public static void main(String[] args) {
Map<Key, String> map = new HashMap<Key, String>();
Key key = new Key("ABC", 1);
map.put(key, "Hello World");

//
Key sameKey = new Key("ABC", 1);
System.out.println(map.get(sameKey));
}
}

// OUTPUT : Hello World
Post a Comment