Reputation: 25
I have a POJO something like the one mentioned below. Here I'm referring Set
collection attribute in POJO1
. I understand that set does not contain duplicate. Do I need to override equals()
and hashCode()
methods in POJO2
? Using a Set
here is not really going to helpful unless we override equals and hashCode methods? Please help me to understand little bit more on this context!
public class POJO1 {
private String name;
private Set<POJO2> pj2;
public Company(){
pj2 = new HashSet<>();
}
//setter and getter methods
}
Upvotes: 0
Views: 940
Reputation: 8758
Yes the only way for Java to understand which objects are duplicates is to call equals()
method. Default implementation of equals()
checks that references of two objects point to the same location in memory.
But depending on exact implementation of your Set
you might need to override hashCode/equals
or implement Comparable
interface.
Since you put objects of POJO2
into HashSet
you need to verride hashCode
equalsmethods in
POJO2` class.
Upvotes: 1
Reputation: 52626
You do like this
import java.util.Set;
public class POJO1 {
private String name;
private Set<POJO2> pojo2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<POJO2> getPojo2() {
return pojo2;
}
public void setPojo2(Set<POJO2> pojo2) {
this.pojo2 = pojo2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
POJO1 pojo1 = (POJO1) o;
if (name != null ? !name.equals(pojo1.name) : pojo1.name != null) return false;
return pojo2 != null ? pojo2.equals(pojo1.pojo2) : pojo1.pojo2 == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (pojo2 != null ? pojo2.hashCode() : 0);
return result;
}
}
Learn more at https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#equals(java.lang.Object)
Upvotes: 0