That is not really the case in my program - I will briefly try to explain
the situation.
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.
Regards,
George
On Tue, 17 Jul 2007 Lekeas GK wrote...
|From: Patricia Shanahan <
[email protected]>
|Date: Tue, 17 Jul 2007 13:18:19 -0700
|Subject: Re: HashTable
|
|George wrote:
|> I am refering to the classes available from java.util, you are right. But
|> if you construct a hashset containing objects o1 and o2 (assume any type
|> of objects) and a second hashset containing their clones, would the
|> hashcodes of the objects (and hence the hashcode of the hashset containing
|> them) be the same?
|>
|> It would seem logical to me that the answer to this question should be
|> positive, but the results of my code suggest otherwise...
|
|These paragraphs strongly imply that you consider clones to be equal.
|That means two distinct instances of your class can be equal, so the
|Object equals and hashCode behavior is completely wrong for that class.
|You do need to override.
|
|> By overiding equals and hashCode, I get something more closer to the
|> result I want but a bit further from what I would assume as correct
|> behaviour. If you could provide any explanation as to why the answer to my
|> assumption above shoulbe no, I would be grateful.
|
|"something more closer" suggests that you are not there yet. If so, I
|suggest doing the following:
|
|1. Write a trivial hashCode() that always returns zero.
|
|2. Concentrate on equals. Think carefully about what determines whether
|an instance of your class is equal to another object, and implement that
|test as your equals method.
|
|The hash-based collections work correctly, but inefficiently, with a
|trivial hashCode().
|
|Once you are sure equals is correct, go back and implement hashCode so
|that all equal instances have the same hashCode while minimizing
|collisions between unequal objects.
|
|Patricia
|