Reputation: 81
I am using a HashSet to add unique Users to the hashset. These users are updated frequently from an online source and when it reads it in from there it gets a new object each time so all the Users get added again.
I have a UserID variable in my user class and would like to use this to add users to the HashSet and ensure uniqueness.
private HashSet<User> userHashSet = new HashSet<User>();
userHashSet.add(user);
//based on the users id it will either add or not
I want to do this without losing efficiency and preferably only one HashSet
Upvotes: 0
Views: 299
Reputation: 54306
You need to implement the hashCode
and equals
methods in your User
class. So long as you implement those two methods correctly then you will get unique entries in your HashSet
.
There are many articles about how to implement these correctly (e.g. What issues should be considered when overriding equals and hashCode in Java?), but the easiest way to do it is to get your IDE to auto-generate those methods, or use the Apache Commons helpers.
Upvotes: 1
Reputation: 5067
You should implement the equals
and hashCode
method in your User
class.
As an example:
@Override
public int hashCode() {
return getUserId().hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof User &&
getUserId().equals(((User) obj).getUserId());
}
Upvotes: 4