This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Detecting and rejecting duplicate grades using equals and hashCode

 
pamela jones
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have written equals and hashCode methods to a class. It is suppose to detect and reject duplicate grades entered into the JPanel. When you press the View button it should show up only once but it shows up twice. I am bewildered. I have included the code I wrote. Please advise.
public boolean equals(Object o){
if (this == o){
return true;
}
if (! (o instanceof Gradeable)){
return false;
}

Gradeable other = (Gradeable) o;
return this.maxPoints == other.maxPoints
&& this.earnedPoints == other.earnedPoints
&& this.description.equals(other.description)
&& this.date.equals(other.date);
}

/**
* This method overrides the Object hashCode method.
* @return the hash code for the Object
*/
public int hashCode() {
int result = 17;

result = 37 * result + maxPoints;
result = 37 * result + earnedPoints;
result = 37 * result + description.hashCode();
result = 37 * result + date.hashCode();
return result;
}
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code here looks good. It's hard to say where the problem is; it's probly somewhere in the code you haven't shown here though. Try finding (or creating) some specific Gradeable objects which you believe should be equal, and insert a line of code to evaluate whether obj1.equals(obj2) and print the result. And print out the values of all the fields being compared. One way to do this is to just insert some code into the equals() method and look at the output:

Hopefully this will give some cluse about what the problem is.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic