Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #17805

Re: hashCode

From "Jan Burse" <jan.burse@1:261/38.remove-nlb-this>
Subject Re: hashCode
Message-ID <502943B3.56755.calajapr@time.synchro.net> (permalink)
Newsgroups comp.lang.java.programmer
Date 2012-08-13 18:36 +0000
Organization tds.net

Show all headers | View raw


  To: Jan Burse
From: "Jan Burse" <jan.burse@1:261/38.remove-m2z-this>

  To: Jan Burse
From: Jan Burse <janburse@fastmail.fm>

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

-+- 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

--- 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

Back to comp.lang.java.programmer | Previous | Next | Find similar | Unroll thread


Thread

Re: hashCode "Jan Burse" <jan.burse@1:261/38.remove-nlb-this> - 2012-08-13 18:36 +0000

csiph-web