schoolcoder
schoolcoder

Reputation: 1654

Finding if a Set containing a given object or not

A Set contains only one object of entity Community and i am using two objects of same value and one of the objects is stored in that Set

Set<Community> communties = template.get(User.class, "1").getCommunities();
Community com = template.get(Community.class, 1);

for(Community community : communties)
        System.out.println(community.equals(com));

System.out.println(communties.contains(com));

First Statement prints true but Second Statement prints false. Why?

Upvotes: 0

Views: 80

Answers (1)

xxxxxxxxx
xxxxxxxxx

Reputation: 1019

You must override hashCode() as well as equals(), otherwise, the Set won't find the correct bucket for the object and will not even arrive to the equals() comparison.

You can use Eclipse "Source" menu to generate pretty decent equals() and hashCode() methods.

Upvotes: 2

Related Questions