Saturday, 15 September 2012

hashCode() called on array instance in Java -



hashCode() called on array instance in Java -

this question has reply here:

java array hashcode implementation 4 answers

i writing code, , came across warning in netbeans:

hashcode() called on array instance

it occurred in piece of code:

public class someobject { private string a; private char[] b; @override public boolean equals(object anotherobject) { if (!(anotherobject instanceof someobject)) { homecoming false; } someobject object = (someobject) anotherobject; homecoming (this.a.equals(object.a) && arraysareequal(this.b, object.b)); } // when created equals() method, netbeans warned me: // 'generate missing hashcode()'. okay then, here comes: @override public int hashcode() { homecoming (43 * this.a.hashcode() + 11 * this.b.hashcode()); // marked line. } }

the warning occurs on marked line. ide finds should avoid calling hashcode() on array instance.

now why should avoid using hashcode() on array?

notice read this question , answer, didn't mention this.

java arrays straight derived java.lang.object , inherit methods equals , hashcode it.

the default equals method compares object identity (i.e. whether 2 references refer same object), , default hashcode method homecoming different values different objects.

in cases, behavior not want. want compare arrays based on content. note, equals method seems that, in turn means hashcode method broken. @ method's documentation reason.

java provides class helper methods reason: java.util.arrays. provides methods equals , hashcode both based on content of array.

so should write that:

public class someobject { private string a; private char[] b; @override public boolean equals(object anotherobject) { if (!(anotherobject instanceof someobject)) { homecoming false; } someobject object = (someobject) anotherobject; homecoming (this.a.equals(object.a) && arrays.equals(this.b, object.b)); } @override public int hashcode() { homecoming (43 * this.a.hashcode() + 11 * arrays.hashcode(this.b)); } }

java arrays hashcode

No comments:

Post a Comment