Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!news-in-01.newsfeed.easynews.com!easynews.com!easynews!news-out.news.tds.net!newsreading01.news.tds.net!53ab2750!not-for-mail From: "Joshua Cranmer" Subject: Re: hashCode Message-ID: <5027F2CB.56703.calajapr@time.synchro.net> X-Comment-To: bob smith Newsgroups: comp.lang.java.programmer In-Reply-To: <50269FCE.56638.calajapr@time.synchro.net> References: <50269FCE.56638.calajapr@time.synchro.net> X-FTN-AREA: COMP.LANG.JAVA.PROGRAMMER X-FTN-MSGID: 1:261/38 51718d47 X-FTN-REPLY: 1:261/38 225e14ea Content-Type: text/plain; charset=IBM437 Content-Transfer-Encoding: 8bit X-Gateway: time.synchro.net [Synchronet 3.16a-Win32 NewsLink 1.98] Lines: 40 Date: Sun, 12 Aug 2012 18:58:20 GMT NNTP-Posting-Host: 69.21.70.65 X-Complaints-To: news@tds.net X-Trace: newsreading01.news.tds.net 1344797900 69.21.70.65 (Sun, 12 Aug 2012 13:58:20 CDT) NNTP-Posting-Date: Sun, 12 Aug 2012 13:58:20 CDT Organization: tds.net X-Received-Bytes: 2847 Xref: csiph.com comp.lang.java.programmer:17758 To: bob smith From: Joshua Cranmer On 8/10/2012 6:22 PM, bob smith wrote: > Better in the sense that you would never HAVE to override hashCode. > > Now, there are cases where you HAVE to override it, or your code is very broken. Returning a constant hash code is correct in the same sense that answering "yes" to the question "Can you tell me the correct way to do this?" would be--syntactically and semantically correct, but completely contrary to the actual intent of the question. The point of the hash code is to provide a cheap way to quickly distinguish inputs (in the sense that Pr(a.hashCode() == b.hashCode() and !a.equals(b)) should be as small as possible [1]). A constant-value hash completely negates the purpose of the hash code, and this renders the hashCode again completely unusable for anything that actually wants to use it. In the default case, a.hashCode() == b.hashCode() only when a == b (this definitely holds true with 32-bit machines and I'm pretty sure it still holds true with 64-bit machines, but I'd have to reverify the JVM source code to be certain). It is thus correct so long as identity equals is correct. It is also potentially correct in a limited set of cases where a.equals(b) and a != b. In all of these cases, it would not only be correct but also extremely useful, having pretty strong guarantees about the distribution of hash values. [1] Actually, for good performance, hash codes should go one step further and make slightly stronger guarantees about independence with respect to the size of the hash table. But I digress. -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth --- 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