Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!postnews.google.com!glegroupsg2000goo.googlegroups.com!not-for-mail From: Lew Newsgroups: comp.lang.java.programmer Subject: Re: hashCode Date: Fri, 10 Aug 2012 12:45:07 -0700 (PDT) Organization: http://groups.google.com Lines: 42 Message-ID: References: <563f186a-edb3-4311-ae48-3af7decfce2c@googlegroups.com> NNTP-Posting-Host: 69.28.149.29 Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable X-Trace: posting.google.com 1344627907 9911 127.0.0.1 (10 Aug 2012 19:45:07 GMT) X-Complaints-To: groups-abuse@google.com NNTP-Posting-Date: Fri, 10 Aug 2012 19:45:07 +0000 (UTC) Cc: Roedy Green In-Reply-To: Complaints-To: groups-abuse@google.com Injection-Info: glegroupsg2000goo.googlegroups.com; posting-host=69.28.149.29; posting-account=CP-lKQoAAAAGtB5diOuGlDQk0jIwmH0T User-Agent: G2/1.0 Xref: csiph.com comp.lang.java.programmer:17654 Roedy Green wrote: > bob smith wrote, quoted or indirectly quoted someone > who said : >=20 >> @Override > > public int hashCode() { > > return 1; > > } >=20 > that's about the worst possible hashCode function. Normally that's correct, but it's conceivable that one might do it for=20 some hackish reason. In most situations where one might do such=20 an override as this, one would do better not to override hashCode(). > See http://mindprod.com/jgloss/hashcode.html for tips on how to write > good ones. The default of assembling it via the mix-in of attribute hash codes=20 using the Knuth constants is usually good enough. h(object) =3D Sum(i =E2=88=88 0.. n-1) of ( attribute[i] * pow(31, n - 1 - = i) ); or=20 public static int calculateHash(Foo arg) { int h =3D 0; for ( each attribute of Foo that contributes to 'equals()' ) { h =3D 31 * h + attribute.hashCode(); } return h; } http://en.wikipedia.org/wiki/Hash_function http://en.wikipedia.org/wiki/Java_hashCode() http://en.wikipedia.org/wiki/Java_hashCode()#Java --=20 Lew