Reputation: 63
If I want generate a hash for a given object in Java, the easiest way I know is to use the Apache Commons HashCodeBuilder
:
public class Person {
String name;
int age;
boolean smoker;
...
public int hashCode() {
// you pick a hard-coded, randomly chosen, non-zero, odd number
// ideally different for each class
return new HashCodeBuilder(17, 37).
append(name).
append(age).
append(smoker).
toHashCode();
}
}
Is there anything similar in C++?
Upvotes: 3
Views: 419
Reputation: 1673
By the way, the hashCode method does not return an identifier for an object. This is a common misconception. There is nothing to prevent 2 objects of the same class returning the same value. The hashCode is meant for hash table data structures, not for identifying objects. Those are 2 separate concepts.
Upvotes: 0