Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!npeer02.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!nx02.iad01.newshosting.com!newshosting.com!novia!news-out.readnews.com!transit3.readnews.com!news-out.news.tds.net!newsreading01.news.tds.net!53ab2750!not-for-mail From: "Lew" Subject: Re: hashCode Message-ID: <50269FCD.56633.calajapr@time.synchro.net> X-Comment-To: Roedy Green Newsgroups: comp.lang.java.programmer In-Reply-To: <50269FCD.56632.calajapr@time.synchro.net> References: <50269FCD.56632.calajapr@time.synchro.net> X-FTN-AREA: COMP.LANG.JAVA.PROGRAMMER X-FTN-MSGID: 1:261/38 834ffa64 X-FTN-REPLY: 1:261/38 048293ea Content-Type: text/plain; charset=IBM437 Content-Transfer-Encoding: 8bit X-Gateway: time.synchro.net [Synchronet 3.16a-Win32 NewsLink 1.98] Lines: 49 Date: Sat, 11 Aug 2012 18:17:50 GMT NNTP-Posting-Host: 69.21.70.65 X-Complaints-To: news@tds.net X-Trace: newsreading01.news.tds.net 1344709070 69.21.70.65 (Sat, 11 Aug 2012 13:17:50 CDT) NNTP-Posting-Date: Sat, 11 Aug 2012 13:17:50 CDT Organization: tds.net X-Received-Bytes: 2317 Xref: csiph.com comp.lang.java.programmer:17686 To: Roedy Green From: Lew Roedy Green wrote: > bob smith wrote, quoted or indirectly quoted someone > who said : > >> @Override > > public int hashCode() { > > return 1; > > } > > that's about the worst possible hashCode function. Normally that's correct, but it's conceivable that one might do it for some hackish reason. In most situations where one might do such 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 using the Knuth constants is usually good enough. h(object) = Sum(i rnn 0.. n-1) of ( attribute[i] * pow(31, n - 1 - i) ); or public static int calculateHash(Foo arg) { int h = 0; for ( each attribute of Foo that contributes to 'equals()' ) { h = 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 -- Lew --- BBBS/Li6 v4.10 Dada-1 * Origin: Prism bbs (1:261/38) --- Synchronet 3.16a-Win32 NewsLink 1.98 Time Warp of the Future BBS - telnet://time.synchro.net:24