P
Patricia Shanahan
George said:That is not really the case in my program - I will briefly try to explain
the situation.
I'm afraid I don't really understand this remark, because you also say
"even for custom3 objects with exactly the same fields" which also
strongly suggest that two distinct custom3 instances can be equal,
exactly the situation I was talking about.
....I have a custom data structure, say custom1, made up of two string fields
and another custom data type, say custom2. So, there is a series of
custom2 objects creation, then used for a series of custom1 object
creation. The custom1 class also has a static HashTable field, indexed by
a HashSet. The HashSet is constructed in a separate method which has
statements of the type hashsetname.add(new custom3(...)).
When this method finishes, before insertion into the main HashTable I run
a check with containsKey - the problem is that it fails even for custom3
objects with exactly the same fields.
Please offer some advice if you can, as I am stuck at this point for about
a week now and it brought all my work to a halt.
I'm afraid the only advice that will work is essentially the advice
everyone has been giving you.
You need to look VERY closely at the equals implementation for custom3.
First temporarily take hashCode out of the picture by implementing it in
each customN class as follows:
public int hashCode(){
return 0;
}
That will make HashSet inefficient, but make it impossible for hashCode
bugs to prevent correct HashSet operation. When everything is working
functionally you should implement a good hashCode for each class,
matching its equals method.
You need to work through each of your classes, implementing AND TESTING
equals. Make sure you test equals with parameter type Object, not
custom3 etc.
I would begin with custom2, because it seems to be bottom of the
dependency hierarchy. Can two custom2 objects be equal because they have
equal fields, without being the same object? If so, write an equals
method that tests whether they have the same fields.
At each step, make sure you have a overridden hashCode with the trivial
version, and that you have tested equals and are happy with the results.
Once custom3's equals method returns true exactly when you think the two
objects are equal, your HashSet containsKey test will work just fine.
If this advice does not solve your problem, I suggest an SSCCE:
http://www.physci.org/codes/sscce/
Patricia