Dynamically changing hashcode() equals() using HashCodeBuilder and EqualsBuilderFrom WikiJava
This is very useful when you are changing your beans quite often, you don't need to keep changing these methods as well.
In detailsay you want to make a class Person which is a bean. And you need also to put in your class your hashcode and equals methods. In the first instance all you need to do is to make your bean and to produce your methods. If then you want to add a new field to the bean, you will need again to update your hashCode and equals methods accordingly. This is no longer required, as you can use the Apache commons project which distributes (under Apache open source license) public class Person { private String firstName; private String lastName; // getters // ... // setters // ... @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((firstName == null) ? 0 : firstName.hashCode()); result = PRIME * result + ((lastName == null) ? 0 : lastName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Person other = (Person) obj; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; return true; } } Will you change the implementation of hashcode() and equals() when you add the new attribute say salary ? . though it is functionality specific If you want to maintain the uniqness we need to alter the above hascode() and equals() to include salary also ... Apache Commons has come up with two classes which does our job much easier . HashCodeBuilder and EqualsBuilder public class Person { private String firstName; private String lastName; // getters // ... // setters // ... @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } } HashCodeBuilder --> will take care of all fields while generating hashcode of Person class at runtime EqualsBuilder EqualsBuilder --> will take care of all fields while generating hashcode of Person class at runtime
|
