Path: csiph.com!usenet.pasdenom.info!news.albasani.net!.POSTED!not-for-mail From: Jan Burse Newsgroups: comp.lang.java.programmer Subject: Re: hashCode Date: Sun, 12 Aug 2012 12:08:52 +0200 Organization: albasani.net Lines: 49 Message-ID: References: <563f186a-edb3-4311-ae48-3af7decfce2c@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.albasani.net WlxON41jo54eOgIXAgifUL1gsN8gTi5YKBg3NKVLdyuudBKMQCaCgcIzydFBGiXbAYTuyeq9pFdDT0FIBsI4D+33dERj+R6DBpW78hIHMF4rS5nGOyblEZC72kFoylSA NNTP-Posting-Date: Sun, 12 Aug 2012 10:08:52 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="Dgx2XR7q4KhDIiUxeqRXHFmDyU6XEUdBcWzMD72ua5eqNGpl4ZNVAKqG5QhrzE6asmgEBx7sVDV9+3qKwrTg1G4aRhhMXjwsFOwFnL1IyNPtWHclAJ96ix2Kwfpq2FaI"; mail-complaints-to="abuse@albasani.net" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20120715 Firefox/14.0.1 SeaMonkey/2.11 In-Reply-To: Cancel-Lock: sha1:QgUz1qpKK9WD2kpCTZrmwnd+/Ak= Xref: csiph.com comp.lang.java.programmer:17730 Jan Burse schrieb: > Maybe it would make sense to spell out what the contract > for hashCode() is. Those who are interested can read the original text. It is found here: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode%28%29 --------------------------------------------------------------- "If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result." That is: /* invariant that should hold */ if a.equals(b) then a.hashCode()==b.hashCode() ---------------------------------------------------------------- "It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables." That is: /* not implied and thus not required by the invariant */ if a.hashCode()==b.hashCode() then a.equals(b) It is also quite unlikely that a hashCode() would satisfy the later, although the closer it comes to the later, the better it works for HashMap, etc.. ---------------------------------------------------------------- There is no reference to Comparable and the compareTo. If I am not using HashMap or HashSet in my application, and still override equals, I do not need to implement hashCode(). I could for example use TreeMap or TreeSet and implement the Comparable interface. There is a reference to equals() back from Comparable though. http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html Bye