I know this has been asked several times and I promise I have read over 100 articles before resorting to posting. Here is my issue:
I have created my own object (
WorkoutData
). It is made up of several string variables, and integer and a linked list of strings:public class WorkoutData implements Serializable { private static final long serialVersionUID = 878893767880469289L; String workoutLocation; String bodyPart; String exercise; int numOfSets; LinkedList<LinkedList<String>> datesSetsAndReps; }
In case any duplicates ever get into my datafile I am reading the objects into a
LinkedHashSet
. My thinking is that this will automatically eliminate any duplicates.
Of course this isn't working, because each object has its own ID and therefore will not be "equal" to another object. To try to get around this I have overridden the equals
and hashCode
inside my WorkoutData
class.
For some reason it is still not working. Here is how I am loading my linkedHashSet:
for (int iterator = 0; iterator < numberOfWorkouts; iterator++)
tempWorkoutDataSet.add((WorkoutData) in.readObject());
Here are my overridden methods in the WorkoutData
class:
@Override
public boolean equals(Object other)
{
if (other == null)
{
return false;
}
if (this.getClass() != other.getClass())
{
return false;
}
if (!this.workoutLocation.equals(((WorkoutData)other).workoutLocation))
{
return false;
}
if (!this.bodyPart.equals(((WorkoutData)other).bodyPart))
{
return false;
}
if (!this.exercise.equals(((WorkoutData)other).exercise))
{
return false;
}
return true;
}
public int hashCode()
{
return this.workoutLocation.length();
}
The hashset contains duplicates no matter what I try. I think the equals
method is correct, but I freely admit I have no idea what the hashCode
method is meant to accomplish.
This question is NOT a duplicate of "How do I compare strings in Java?". That question only talks about the == vs .equals issue. My issue has more to do with overriding hashCode
. I think that is where my problem lies. Couple that with the fact that I am still unclear exactly what the hashCode
override is meant to accomplish.