I have a bean with 4 attributes:
user institutionId groupId postingDate I use Eclipse to generate equals and hashcode but the resulting code is not pretty. Is there a compact way to do the same? Assuming I want equals & hashcode to use all the attributes or a subset of them.
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); result = prime * result + ((institutionId == null) ? 0 : institutionId.hashCode()); result = prime * result + ((postingDate == null) ? 0 : postingDate.hashCode()); result = prime * result + ((user == null) ? 0 : user.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; ManGroupKey other = (ManGroupKey) obj; if (groupId == null) { if (other.groupId != null) return false; } else if (!groupId.equals(other.groupId)) return false; if (institutionId == null) { if (other.institutionId != null) return false; } else if (!institutionId.equals(other.institutionId)) return false; if (postingDate == null) { if (other.postingDate != null) return false; } else if (!postingDate.equals(other.postingDate)) return false; if (user == null) { if (other.user != null) return false; } else if (!user.equals(other.user)) return false; return true; }
equalsis. If you don't need it all, delete some. IIRC there are some reflective ones as well, alternate generators, and ways to choose which fields are used.Objects.equalsandObjects.hashinjava.utilfor Java >= 7, otherwise google guava has those helpers.