How would you write an equals() method? I need to be able to write a useable one for comparing playing cards in the program. I am using NetBeans for the writting of the code.
I also tend to notice that equals() methods often come with hashCode() methods. What is hashCode meant to do exactly and how should they be written?
So, how should I write an a by-the-book equals() method and a hashCode() method if I need it?
I will post the two equals() methods I ended up doing yesterday, and if anyone needs additional infomation on my program in particular, let me know and I will add the rest.
This is my current set up, unfortantely it will always printout the same output (false).
@Override
public boolean equals(Object otherObject)
{
boolean set = false;
if (!(otherObject instanceof PlayingCard))
{
set = false;
}
if (otherObject == this)
{
set = true;
}
System.out.println(set);
return set;
}
This is (I think) the original equals() method I used.
@Override
public boolean equals(Object otherObject)
{
if (otherObject == null)
{
System.out.println("Match");
return false;
}
if (getClass() != otherObject.getClass())
{
System.out.println("Match");
return false;
}
System.out.println("No Match, True");
PlayingCard other = (PlayingCard) otherObject;
return suit.equals(other.suit) && rank == other.rank;
}