Path: csiph.com!usenet.pasdenom.info!gegeweb.org!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: hashCode Date: Sat, 11 Aug 2012 22:43:31 -0400 Organization: A noiseless patient Spider Lines: 50 Message-ID: References: <563f186a-edb3-4311-ae48-3af7decfce2c@googlegroups.com> <6ac6c252-c370-4f74-b29d-ce5368019977@googlegroups.com> <238731fe-b8c8-482d-b168-56ef9a0531bb@googlegroups.com> <502599a5$0$287$14726298@news.sunsite.dk> <502711b9$0$292$14726298@news.sunsite.dk> <502714fd$0$294$14726298@news.sunsite.dk> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit Injection-Date: Sun, 12 Aug 2012 02:43:38 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="ffb8f7085759b339c1002252b48331a4"; logging-data="10764"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18ir7GFkLIei672Ptr2uvBG" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20120713 Thunderbird/14.0 In-Reply-To: <502714fd$0$294$14726298@news.sunsite.dk> Cancel-Lock: sha1:y/kPasxzs1ak4OOVZ+7IupdHHU0= Xref: csiph.com comp.lang.java.programmer:17725 On 8/11/2012 10:29 PM, Arne Vajhøj wrote: > On 8/11/2012 10:15 PM, Arne Vajhøj wrote: >> This is a classic test question in basic Java SE. And that returning >> a constant is correct but not smart should be in most Java SE >> text books. > > Effective Java / Joshua Bloch: > > > // The worst possible legal hash function - never use! > public int hashCode() { return 42; } > > It is legal because it ensures that equal objects have the > same hash code. It's atrocious because ... > > > Java 2 SUN Certified Programmer & Developer / Kathy Sierra & Bert Bates: > > > A hashCode() that returns the same value for all instances whether > they're equal or not is still a legal - even appropriate - hashCode() > method! For example, > public int hashCode() { > return 1492; > } > would not violate the contract > ... > This hashCode() method is horrible inefficient, ... > ... > Nontheless, this one-hash-fits-all method would be > considered appropriate and even correct because it > doesn't violate the contract. Once more, correct does > not necessarily mean good. > All this means is that people know how to describe a "correct" hashCode(), but nobody knows how to describe a "usable" hashCode() in terms that apply testably to all circumstances. The O.P. asked whether it would "be potentially better" if Object's hashCode() returned a constant. He did *not* ask whether such an implementation would be correct; he only asked if it would "be potentially better." Upon prompting he explained what he meant by "better," and in light of that explanation the answer to his original question is NO. Discussions about "Oh, but it's CORRECT" are just red herrings; it's still not "better." -- Eric Sosman esosman@ieee-dot-org.invalid