S
sasuke
Hello to all Java programmers out there.
I am currently faced with the task of providing a logical equals()
method for my domain / business classes. This job being done, I now
have to override the hashCode() so that when an object of this class
is used as a key in a Map, the Map behavior is well defined.
I have thought of a couple of ways to do this but would like to give
inputs on my thoughts:
public class Agent {
String name;
String code;
Address addr;
/**
* The hash code of Agent is the combined hash code of
* it's constituent elements.
*/
public int hashCode() {
return(name.hashCode() +
code.hashCode() +
addr.hashCode());
}
/**
* The hash code of Agent is the hash code of the
* string representation of it's constituent elements.
* THis is guaranteed to be unique since the string
* representation of no objects is the same unless they
* actually are equal. This approach might also benefit
* from the fact that Strings in case of Java are pooled
* so a hashCode string once calculated for an object will
* remain for it's lifetime in the string pool
*/
public int hashCode() {
return((name + code + addr).toString().hashCode());
}
}
Which approach would be better? The one utilizing the nested calls to
the hashCode() of constituent elements or the String approach? Also
how would I prove whether the hashCode() algorithm chosen by me will
in all cases generate unique hash codes?
Any kind of input / feedback / links / suggestions would be greatly
appreciated.
Thanks and regards,
~/sasuke
I am currently faced with the task of providing a logical equals()
method for my domain / business classes. This job being done, I now
have to override the hashCode() so that when an object of this class
is used as a key in a Map, the Map behavior is well defined.
I have thought of a couple of ways to do this but would like to give
inputs on my thoughts:
public class Agent {
String name;
String code;
Address addr;
/**
* The hash code of Agent is the combined hash code of
* it's constituent elements.
*/
public int hashCode() {
return(name.hashCode() +
code.hashCode() +
addr.hashCode());
}
/**
* The hash code of Agent is the hash code of the
* string representation of it's constituent elements.
* THis is guaranteed to be unique since the string
* representation of no objects is the same unless they
* actually are equal. This approach might also benefit
* from the fact that Strings in case of Java are pooled
* so a hashCode string once calculated for an object will
* remain for it's lifetime in the string pool
*/
public int hashCode() {
return((name + code + addr).toString().hashCode());
}
}
Which approach would be better? The one utilizing the nested calls to
the hashCode() of constituent elements or the String approach? Also
how would I prove whether the hashCode() algorithm chosen by me will
in all cases generate unique hash codes?
Any kind of input / feedback / links / suggestions would be greatly
appreciated.
Thanks and regards,
~/sasuke