title: Overriding hashcode method to return hashcode of variable in a class
body: <pre><code>class UserScoring implements Comparable&lt;UserScoring&gt; {
  
          User user;
          int score;
  
          UserScoring(User user, int score) {
              this.user = user;
              this.score = score;
          }
  
          @Override
          public int compareTo(UserScoring o) {
              if (this.score &lt; 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);
          }
      }
  </code></pre>
  
  <p>I want to create a class <code>UserScoring</code> which can be sorted on the basis of its variable score and whose uniqueness is determined by its user.</p>
  
  <p>This means that :</p>
  
  <ol>
  <li>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.</li>
  <li>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.</li>
  </ol>
  
  <p>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?</p>
  
  <ol start="2">
  <li><p>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. </p>
  
  <pre><code>UserScoring us1 = new UserScoring(u1, 1000);
  UserScoring us2 = new UserScoring(u1, 100);
  Set&lt;UserScoring&gt; set = new HashSet&lt;&gt;();
  set.add(us1);
  set.add(us2);
  </code></pre></li>
  </ol>
  
  <p>How can this set contain us1 instead of us2?</p>