Let's say I have the following class A that implements an interface M:
class A implements M {
int i;
int hashCode() { return i; }
}
And a wrapper for A, for example
class AWrapper implements M {
A a;
public Wrapper(A a) {
this.a = a;
}
int hashCode() { ??? }
}
This hierarchy is a sort of Composite Pattern. My question is what is a good hashcode for the AWrapper class? I can use a.hashCode()
, but then all A's and
AWrapper's will have the same hashcode. What is the best way to implement such a hash code?
As some people ask what's the rationale behind this design, let me make it more concrete. I'm writing a data type for regular expressions. So A is a symbol, and there are regular operators such as *, +, ? that are essentially wrappers of symbols, e.g., Star(A). I also want to make sure there is only one instance of an object, that's why I need sharing, so if someone writes:
r1 = a*a
r2 = a*c
represented by Seq(Star('a'), 'a')
and Seq(Star('a'), 'c')
, I want two instances of Star('a')
be shared, of course via a factory call.