Using intermediate array for hashCode and equals

Posted by Basilevs on Stack Overflow See other posts from Stack Overflow or by Basilevs
Published on 2013-10-24T03:50:23Z Indexed on 2013/10/24 3:53 UTC
Read the original article Hit count: 144

Filed under:
|
|
|

As its a pain to handle structural changes of the class in two places I often do:

class A {
  private B bChild;
  private C cChild;

  private Object[] structure() {
    return new Object[]{bChild, cChild};
  }

  int hashCode() {
      Arrays.hashCode(structure);
  }

  boolean equals(Object that) {
    return Arrays.equals(this.structure(), ((A)that).structure());
  }
}

What's bad about this approach besides boxing of primitives? Can it be improved?

© Stack Overflow or respective owner

Related posts about java

Related posts about arrays