class UserScoring implements Comparable<UserScoring> {
User user;
int score;
UserScoring(User user, int score) {
this.user = user;
this.score = score;
}
@Override
public int compareTo(UserScoring o) {
if (this.score < o.score) {
return 1;
}
else if (this.score == o.score) {
return 0;
}
return -1;
}
@Override
public int hashCode() {
return user.hashCode();
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UserScoring other = (UserScoring) obj;
return user.equals(other.user);
}
}
I want to create a class UserScoring which can be sorted on the basis of its variable score and whose uniqueness is determined by its user.
This means that :
- If I sort a collection of UserScoring objects using Collections.sort(), I want the sorting based on score in a descending order. I have overriden the compareTo method for the same.
- If I create a set of the UserScoring objects, I do not want two UserScoring objects of the same user. I have overriden the equals and the hashcode method for the same.
I have two doubts here: 1. Is it wrong to return the hashcode of the UserScoring object the same as the User object. It sure looks wrong to me. But what are the problems it can cause?
Is there any way at all to make sure that only the UserScoring object of the higher score is kept in the set(and the object with less score is either evicted or not added) whenever there is an attempt to add two UserScoring objects of the same user.
UserScoring us1 = new UserScoring(u1, 1000); UserScoring us2 = new UserScoring(u1, 100); Set<UserScoring> set = new HashSet<>(); set.add(us1); set.add(us2);
How can this set contain us1 instead of us2?
hashCode()andequals()implementations not match? They're both just considering theuserfield. What doesn't match up is thecompareToimplementation.equalsmethod says are equal, butcompareTobetween them will not return 0. YourcompareTois not consistent with equality.Map<User, UserScoring>. That way you can look up theUserScoringbased on aUser; have only oneUserScoringperUser; and you can explicitly keep the one with the higher score if that is what you want. Currently you are trying to useequalsto group objects that you don't really consider equal.