Reputation: 93
Probably a common problem I'm not sure has a solution in Java
Say we have Class A, Class B, and Class C. Where B and C extend A.
We have a
Set<A>
A has a simple hashcode based on the properties of A. My problem is when I'm adding B and C to the set, where B and C may have the same properties as each other with respect to A.
Obviously B has some properties C doesn't and C has some properties B doesn't. The problem is I am not able to add B and C to the set because their hashcode (using A's hashcode function) will be the same. And for reasons (not explaining here) I am not allowed to remove anything from Set A.
My problem really comes down to, we have 2 objects A, one of them really is a B. However, with respect to this set and their hashcode, they are the same. Is there anyway I can express that these 2 As, even if all their A properties are the same, are not actually the same?
What would be nice is if A's hashcode function could be based on what its underlying subclass really is. Is this possible? Anyway around my problem?
Upvotes: 0
Views: 149
Reputation: 41208
Override the hashCode and equals methods in B and C as well.
This way when the hashing comes to compare them it will include their properties as well as delegating down to compare the properties within A.
Upvotes: 3