java - Overriding equals and hashCode on a POJO with a List object -
i have 2 pojos this
public class element{ private string name; private int number; //getters , setters } public class container{ private string subject; private string email; private list<element> elements; //getters , setters }
and need verify if 2 container objects same. looked bit , found apache commons has hashcodebuilder , equalsbuilder overriding methods. idea builder methods use elements in object in order determine hashcode , equality of 2 objects. problem that, if see example code, looks this:
public boolean equals(object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getclass() != getclass()) { return false; } myclass rhs = (myclass) obj; return new equalsbuilder() .appendsuper(super.equals(obj)) .append(field1, rhs.field1) .append(field2, rhs.field2) .append(field3, rhs.field3) .isequals(); }
how can append list<element> elements
? need create method parse whole list string work? thanks!
short version:
yes, can use append
method of equalsbuilder
, hashcodebuilder
.
long version:
the list.equals(object)
method compares elements on list. see javadoc
compares specified object list equality. returns true if , if specified object list, both lists have same size, , corresponding pairs of elements in 2 lists equal. (two elements e1 , e2 equal if (e1==null ? e2==null : e1.equals(e2)).) in other words, 2 lists defined equal if contain same elements in same order. definition ensures equals method works across different implementations of list interface.
so use append(elements, rhs.elements)
compare lists.
the list.hashcode()
use hashcode of elements, can use append
method of hashcodebuilder
. javadoc says:
returns hash code value list. hash code of list defined result of following calculation:
int hashcode = 1; (e e : list) hashcode = 31*hashcode + (e==null ? 0 : e.hashcode());
Comments
Post a Comment