Implementing Hash Code

Hi all!
I found myself implementing hashCode and equals methods for a class, and googled a little bit looking for a good implementation.
I found that the most used is this one:
public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((Int1 == null) ? 0 : Int1.hashCode());
            result = prime * result + ((Int2 == null) ? 0 : Int2.hashCode());
            result = prime * result + ((Int3 == null) ? 0 : Int3.hashCode());
            result = prime * result + ((Int4 == null) ? 0 : Int4.hashCode());
            result = prime * result + ((Int5 == null) ? 0 : Int5.hashCode());
            result = prime * result + ((Int6 == null) ? 0 : Int6.hashCode());
            result = prime * result + ((Int7 == null) ? 0 : Int7.hashCode());
            return result;
      }Actually, this exact code was generated automatically by Eclipse tools for a test class I made.
What I found alarming, is that, in such an implementation, that prime variable, is multiplied by itself in every row!
This is what result equation would look like:
result = prime^7 + prime^6*Int7.hashCode() + prime^5*Int6.hashCode() + ... (where prime^n means a power).
And, translating it into numbers, we have that:
result > prime^7 = 31^7 = 27,512,614,111 > 2,147,483,647 = MAX VALUE OF JAVA PRIMITIVE INT!!!!
I don’t want to think about classes with 10 or 20 fields!!
I’m not sure about how java faces a value over its maximum, but, anyway I think that, over 6 fields, this implementation is a bit “HEAVY” for an int hashCode…
Obviously, you can change the 31 for a lower prime, but don’t think there would be much difference in that.
These would be the maximum valid number of fields for the corresponding primes:
31 – 6
29 – 6
23 – 6
19 – 7
17 – 7
13 – 8
A part from that, although it covers pretty fast the whole int range, there's no consistency about collisions, so it's far form being a "perfect" hash code ( an utopic hash code implementation that returns a unique value for each different instance of a class ).
So, thinking about a better implementation I came into this:
public int hashCode() {
            double result = Math.pow(2,((Int1 == null) ? 0 : Int1.hashCode()));
            result *= Math.pow(3,((Int1 == null) ? 0 : Int1.hashCode()));
            result *= Math.pow(5,((Int1 == null) ? 0 : Int1.hashCode()));
            result *= Math.pow(7,((Int1 == null) ? 0 : Int1.hashCode()));
            result *= Math.pow(11,((Int1 == null) ? 0 : Int1.hashCode()));
            result *= Math.pow(13,((Int1 == null) ? 0 : Int1.hashCode()));
            result *= Math.pow(17,((Int1 == null) ? 0 : Int1.hashCode()));
            return (int) result;
      }but I guess that, although there would be absolutely no collision its cost would be too much for optimizing hash tables searches.
So, what do you think about it?
Or better...Does anyone thought of it before? and Did you get into a better implementation?
Thanx, and good programming!

Well, let me explain...
And I don't know what exactly you mean by "HEAVY".I meant in terms of size of the value. Obviously, what I suggested is really a lot more expensive ( in temps of computation costs ), but it was only an example that guarantees unicity.
The algorithm you describe is widely used and usually considered to be the best general-purpose algorithm that can be applied to pretty much all classes.Chapter 3 of Effective Java (= the go-to-place for information on equals() and hashCode()) also describes that algorithm. >
Well, that's what I've seen, that this is the most commonly accepted algoritm, but what I wonder is why it is so common, and which is its Mathmatical consitency.
If you have a look at the expression I wrote, there's absolutelly no control over the unicity of that algoritm. Off course this is not a problem, as it fits the hash code contract, returning different values for different elements, but, I question why to make such a "big" product when there's plenty of collisions anyway!
Look at what you refered:
>
"The multiplication in step 2.b makes the hash value depend on the order of the
fields, which results in a much better hash function if the class contains multiple
similar fields. For example, if the multiplication were omitted from a String hash
function built according to this recipe, all anagrams would have identical hash
codes. The multiplier 37 was chosen because it is an odd prime. If it was even and
the multiplication overflowed, information would be lost because multiplication
by two is equivalent to shifting. The advantages of using a prime number are less
clear, but it is traditional to use primes for this purpose.""The multiplication in step 2.b makes the hash value depend on the order of the
fields, which results in a much better hash function if the class contains multiple
similar fields. For example, if the multiplication were omitted from a String hash
function built according to this recipe, all anagrams would have identical hash
codes. The multiplier 37 was chosen because it is an odd prime. If it was even and
the multiplication overflowed, information would be lost because multiplication
by two is equivalent to shifting. The advantages of using a prime number are less
clear, but it is traditional to use primes for this purpose.">
Even here it is said that there's absolutely no consistent reason for taking such an approach! (or, at least, I don't see it).
For example, in case of the class I was talking about, take a look at this:
public int hashCode() {
            int result = 2 * ((Int1 == null) ? 0 : Int1.hashCode());
            result += 3 * ((Int2 == null) ? 0 : Int2.hashCode());
            result += 5 * ((Int3 == null) ? 0 : Int3.hashCode());
            result += 7 * ((Int4 == null) ? 0 : Int4.hashCode());
            result += 11 * ((Int5 == null) ? 0 : Int5.hashCode());
            result += 13 * ((Int6 == null) ? 0 : Int6.hashCode());
            result += 17 * ((Int7 == null) ? 0 : Int7.hashCode());
            return result;
      }I really haven't calculated it, but I suspect that number of collisions would be equivalent to the given by the other algoritm, and its values would remain smaller than in the other case.
In fact, you could even change the prime numbers for the Integers succession: 2,3,4,5,6,7....
So, my question is...Why that algoritm? Which are the advatages of an algoritm that works with such a Big values?
thanks!

Similar Messages

  • Urgent: please help - Object Hash Code of RMI stubs in a cluster

    Hello all,
    I'm trying to find out for a week now if members of a cluster can get out of synch
    regarding "Object Hash Code" of RMI stubs in the JNDI.
    After binding an RMI object to one server (no rmic performed since the object
    is in the classpath of both servers and the service is pinned), the JNDI mapping
    looked identical on both servers.
    However, while one server went down for a few hours, the other server has changed
    the "Object Hash Code" to a new one (the binding name stayed constant). When the
    server went up again it tried to lookup the object under the same binding, then
    found it but failed to execute remote methods on it. An error message says that
    the object was garbage collected:
    java.rmi.NoSuchObjectException: Unable to dispatch request to Remote object with
    id: '347'. The object has been garbage collected. at weblogic.rjvm.RJVMImpl.dispatchRequest(RJVMImpl.java:766)
    at weblogic.rjvm.RJVMImpl.dispatch(RJVMImpl.java:738) at weblogic.rjvm.ConnectionManagerServer.handleRJVM(ConnectionManagerServer.java:207)
    at weblogic.rjvm.ConnectionManager.dispatch(ConnectionManager.java:777) at weblogic.rjvm.t3.T3JVMConnection.dispatch(T3JVMConnection.java:508)
    at weblogic.socket.NTSocketMuxer.processSockets(NTSocketMuxer.java:664) at weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:23)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:213) at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:189)
    Why isn't the new JNDI mapping replicated to the new booting server? Should I
    use specific rmic flags? How can I maintain the JNDI trees identical on all clustered
    servers?
    I'm using two managed WLS 7.02 servers running on win2000 servers.
    Dani

    Hi Andy,
    Thank you for responding.
    The binding code looks like that:
    m_ctx = new InitialContext();
    int index = getNextAvailableRepositoryJNDIIndex();
    m_ctx.bind(
    NODE_PREFIX+index,
    this
    where this is the Remote implementation.
    How will I make the object hash code constant or have all views remain constant
    when the GC changes its reference?
    Dani
    Andy Piper <[email protected]> wrote:
    "Daniel Gordon" <[email protected]> writes:
    I'm trying to find out for a week now if members of a cluster can getout of synch
    regarding "Object Hash Code" of RMI stubs in the JNDI.The hash code can probably change since the stub represents an
    aggregate view of the cluster. But this may be a red-herring. What
    does your code look like that binds the rmi object? It may be that DGC
    is biting you.
    andy

  • MD5 hash code in PLSQL

    Hi everyone,
    I am building dynamic web pages using Oracle's plsql web
    toolkit. I am building a page that will pass information to a
    credit card authorizer. I need to create a MD5 hash string to
    pass to the credit card company. Is there an Oracle built in
    procedure/function/package to generate a MD5 hash string? If
    not, can anyone recommend a good reference source for generating
    a MD5 hash code in a plsql environment.
    Thanks.
    Dave W.

    This is from the Object API; I think it has the information that explains what's happening (but doesn't resolve your apparent problem)
    public int hashCode()
    Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.
    The general contract of hashCode is:
    Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
    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.
    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 hashtables.
    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

  • Implementing Hash tables with chaining.

    Hi, I'm in a Java data structures class right now and we have a program to do using hash tables. I've read about hash tables and chaining but does anyone know where i can find some examples of code that implement hash tables using chaining. It's all very confusing to me without seeing how it is used in a program.
    To give you an idea of what we're doing, the assignment is to create a word processor that looks thru a file and adds different words to the table and also counts how many of each word there is in that file. Keep in mind I'm not asking for the code to this assignment just for some example of how coding hash tables/chaining works.

    Simple and probably not complete overview:
    Suppose you have an array in which you will store objects.
    You take an object, and find a "hash code" for it. You then restrict the hash code in to the range of your array. This gives you the index where you can store your object.
    But what if another object is already present at that index?
    Different solutions to this exist - such as re-hashing. One solution is "chaining". Instead of storing the object directly at the hashed index - you store a list of objects which hashed to the same location.
    When you do a lookup, you first get your hash. You then look at the corresponding location in the array. If you find a list rather than the required object, you walk along the list until you find the object you are looking for.
    Of course, with a small array and bad hash distribution, the performance of this solution can degrade fairly quickly.
    BTW, in the real world, just use one of the ready made collections in java.util.

  • Best way to implement this code in labview

    Hi
    What is the best way to implement this code in labview programming.
    I have an analogue input which triggers a boolean light when it reaches a certain voltage. but at the same time i would like it to enable two other outputs one for a set period of time and the other stay on until another statement becomes true.
    For example
    case 1:
    Set output high
    Delay(2000ms)
    Set output low
    Case 2:
    Set output high
    If statement 2 is true
    then set out put low
    if not then repeat until statement is true
    Thanks for your help

    Hi David,
    The code you posted will work, although note that the front panel becomes 'unresponsive' - as changes in the controls are only read once per iteration.  The wait function is an example of an execution timing VI, however if we want to do software timing (like a 2 hour wait) - we should use software timing VIs.
    Check out the following example (note we can stop execution during run-time):
    Regards,
    Peter D
    Attachments:
    SoftwareTiming.vi ‏26 KB

  • How to implement bar code in Unix environment - EBS 11.5.8 ?

    Hi All,
    I need to implement bar codes in an AR Invoice in Unix environment. I have barcode.pfa that is the font file. Is the equivalent file from ttf file in windows environment.
    I have read different papers in metalink that say that for example the name of the directory is this /usr/lib/X11/fonts/type1, but in my AIX server I haven't found something similar like this.
    I wrote this statement in order to find the directory but I didn't find it.
    find . -name fonts -print (fonts is the name of the directory)
    Can you help me?
    Best Regards,
    Mariano.-

    Hi Hussein,
    I've read Note: 466531.1 - How To Implement An AFM / PFA Barcode or MICR Font Within A UTF8 EBS Instance. It says that I have to
    copy the Barcode.pfa to the ORACLE_HOME directory. However, in this directory I don't have another pfa or ttf file, so how can unix relate the font?
    Best Regards,
    Mariano.-

  • What is the hash code?

    What is the hash code of an object? What does hash code mean?

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Obje
    ct.html#hashCode()also http://en.wikipedia.org/wiki/Hash_code
    what the hashcode isn't, though, is an identifier for an object, unique or otherwise. don't make that mistake!
    "Database Systems" by Connolly-Begg has a good section on hash codes and their uses, if memory serves me well

  • What is hash code in Java and how it is related to equals method

    Can any body give me the detailed information about hashcode and the relationship between equals method and hash code.

    Objects in Java have hash codes associated with them. An object's hash code is a signed number that identifies the object (for example, an instance of the parent class). An object's hash code may be obtained by using the object's hashCode() method as follows:
    int hashCode = SomeObject.hashCode();
    The method hashCode() is defined in the Object class and is inherited by all Java objects. The following code snippet shows how the hash codes of two objects relate to the corresponding equals() method:
    1. // Compare objects and then compare their hash codes
    2. if (object1.equals(object2)
    3. System.out.println("hash code 1 = " + object1.hashCode() +
    4. ", hashcode 2 = " + object2.hashCode());
    5.
    6. // Compare hash codes and then compare objects
    7. if (object1.hashCode() == object2.hashCode())
    8. {
    9. if (object1.equals(object2))
    10. System.out.println"object1 equals object2");
    11. else
    12. System.out.println"object1 does not equal object2");
    13. }
    In lines 3-4, the value of the two hash codes will always be the same. However, the program may go through line 10 or line 12 in the code. Just because an object's reference equals another object's reference (remember that the equals() method compares object references by default), it does not necessarily mean that the hash codes also match.
    The hashCode() method may be overridden by subclasses. Overriding the hash code will allow you to associate your own hash key with the object.

  • What is "hash code"?

    hashCode() is available in most of the classes in Java API.
    What is "hash code"?
    Thanks!

    From the page
    http://java.sun.com/docs/books/tutorial/java/javaOO/objectclass.html
    "The value returned by hashCode is an int that maps an object into a bucket in a hash table. An object must always produce the same hash code. However, objects can share hash codes (they aren't necessarily unique)."

  • Object hash code help

    Will two identical objects that return identical hash codes regardless of how many times the program is run? For instance, will a String that contains for example "Test" have an identical hash code as another String that contains "Test" but was run in a different instance of the program? The reason I want to know is that I'm using the hashcode to create a primitive checksum of my saved file to check for when I load it.

    For strings this is true, but aren't Strings a special case,
    since the hashcode is generated from the charecters in the
    string. If you use other objects that get initialized the
    same way will this still be true?

  • Help needed in calculating hash code for a linked list??

    I have reffered API documentation for the list interface...There i found the code below for the hashcode() method ...I couldn't get why "31" is used as a multiplicative factor?
           int hashCode = 1;
           Iterator<E> i = list.iterator();
           while (i.hasNext()) {
               E obj = i.next();
               hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
           }I'm a beginner....please help me out..

    Because it's a prime number, I think. You'll probably want to find an article or decent book on creating optimal hash functions.

  • How to implement this code in labview?

    How do implement this pseudo code in labview? Please keep in mind "a" and "c" in the code below ARE VARIABLES
    for i =0 to i=maxvalue
           if i <= a 
               output = output2
           else if i > a AND i<=c
               output = output2
           else if i < c 
               output = output3
           else i = d
               output = output4
    I understance i can use a case structures and modify the label, but i do not know how to make the label dependent on a variable value. 
    Thanks 

    Try an array of boudaries and use threshold array. See this old example:
    Now just iterate over an array of values using a FOR loop.
    LabVIEW Champion . Do more with less code and in less time .

  • To implement bar code in print out of form script

    hi
    can any one tell me steps to implement the bar code for a field in  sap script layout
    what code should is put and process step by step
    quick answeres will be rewarded with points kindly let me know asap
    regards
    Arora

    first u need to create a bar code charcter format and then user the charcter format which field u want to use it to.
    make sure that u printer supports barcode printing.
    if  ur printer is a Zebra printer then u need to write the code in in zebra printing code.
    Regards
    Devanand

  • MIDP 2.0 reference Implementation Strange code

    I' ve found a strange code in the http/Protocol.java of the Reference MIDP 2.0 Implementation.
    Line 139 in the static initializer.
    prop = Configuration.getProperty(
                                "com.sun.midp.io.http.max_persistent_connections");
            if (prop != null) {
                try {
                    temp = Integer.parseInt(prop);
                    if (temp <= 0) { //!!!!
                        maxNumberOfPersistentConnections = temp;
                } catch (NumberFormatException nfe) {
                    // keep the default
            }Can somebody explain me, why it looks so? It must be ">".
    Additionally, it looks like WTK22 emulator don't understands the property.

    No ideas?

  • Implementing Database codes FAIL /error in parsing data into jsp page

    Hi there,
    I have this problem trying to build a portal application. I am using the JSPDynPage, jsp page and a bean to build a page.
    I have this problem parsing data from JSPDynPage to the beans and to the jsp page.
    I tested out the connection between the beans and the jsp page. There is no error parsing information from the beans to the jsp page.
    So i tried to test out the codes for the database from the beans.
    Will this work? Because it does not display the results i want.
    I need an Solution asap to find out wad is wrong also also the correct codes to the database.
    public String db(){
    try {
                 InitialContext iC = new InitialContext();
                 DataSource dataSource = (DataSource)iC.lookup("java:env/jdbc/mySQL");
                 java.sql.Connection connection = dataSource.getConnection();
                 PreparedStatement st = connection.prepareStatement("SELECT name FROM test WHERE id='123'");
                 ResultSet resultSet = st.executeQuery();
                 while (resultSet.next()){
                      name = resultSet.getString("name");
                      name = name.toString();
                 connection.close();
                 return name;
                 } catch(Exception n){
                      e = "Exception";
                      return e;
    This is the method i put in the beans to test out the database connection.
    Thanks Loads
    Quatre

    Hi there,
    Thanks for the reply, i thought that no one is going to reply me anymore. Thanks loads.
    Bean Class name: Bean1
    Bean Packeage name: Beans1
    Bean id : myBean1
    Jsp Codes
    <%@ taglib uri="tagLib" prefix="hbj" %>
    <jsp:useBean id="myBean1" scope="application" class="Beans1.Bean1" />
    <hbj:content id="myContext" >
      <hbj:page title="PageTitle">
       <hbj:form id="myFormId" >
       <hbj:textView id = "ll" text="lalalalalalalalalasasa" />
      <%--
    <hbj:textView id = "l">
                   <% l.setName(myBean1.getName());%>
    </hbj:textView>
    --%>
    <hbj:textView
                    id="appraisal_yr_label"
                    text="Apprasial Year:">
                    </hbj:textView>
                    <hbj:textView id = "la" >
                    <% la.setText(myBean1.getName());%>
                    </hbj:textView>
       </hbj:form>
      </hbj:page>
    </hbj:content>
    Beans1.java
    package Beans1;
    import java.io.Serializable;
    public class Bean1 implements Serializable{
    private String name = new String();
    private String e = new String();
    private String year = new String();
         public void setName(String name){
              this.name = name;
         public String getName(){
              return name;
    JSPDynPage
    import Beans1.Bean1;
    import com.sapportals.htmlb.*;
    import com.sapportals.htmlb.enum.*;
    import com.sapportals.htmlb.event.*;
    import com.sapportals.htmlb.page.*;
    import com.sapportals.portal.htmlb.page.*;
    import com.sapportals.portal.prt.component.*;
    public class testDBv5 extends PageProcessorComponent {
    import Beans1.Bean1;
    import com.sapportals.htmlb.*;
    import com.sapportals.htmlb.enum.*;
    import com.sapportals.htmlb.event.*;
    import com.sapportals.htmlb.page.*;
    import com.sapportals.portal.htmlb.page.*;
    import com.sapportals.portal.prt.component.*;
    public class testDBv5 extends PageProcessorComponent {
      public DynPage getPage(){
        return new testDBv5DynPage();
      public static class testDBv5DynPage extends JSPDynPage{
        private Bean1 myBean1= null;
        private String name = new String();
        public void doInitialization(){
              try{
                                  IntitialContext context = new javax.naming.InitialContext();
                                  DataSource dataSource = (DataSource)context.lookup("java:env/jdbc/appDB");
                                  Connection connection = dataSource.getConnection();
                                  Statement stmt = connection.createStatement();
                                  ResultSet rs = stmt.executeQuery("Select AppraisalYear From tblAppraisal Where AppraisalYear='2007'");
                                          while(rs.next()){
                                            year = rs.getString("AppraisalYear");
                                            rs.close();
                                            stmt.close();
                                            connection.close();
                                            return year;
                                       }catch (Exception n){
                                            n.printStackTrace();
              IPortalComponentProfile profile = ((IPortalComponentRequest)getRequest()).getComponentContext().getProfile();
                     Object o = profile.getValue("myBean1");
                     if(o==null || !(o instanceof Bean1)){
                        myBean1 = new Bean1();
                        profile.putValue("myBean1",myBean1);
                     } else {
                          myBean1 = (Bean1) o;
                        Object value = request.getSession().getValue("myBeans1");
                        if (value==null || (value instanceof Bean1)){
                             myBean1 = new Bean1();
                        request.getSession().putValue("myBean1", Object value);
              DataBase cn = new DataBase();
              name = cn.dataBaseConnection();
              myBean1.setName(name);
    //name = "gir";
    //myBean1.setName(name);
    // IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
    //IPortalComponentContext myContext = request.getComponentContext();
    //Bean1 myNameContainer = (Bean1) myContext.getValue("myBean1");
    //myNameContainer.setName(name);
          // fill your bean with data here...
        public void doProcessAfterInput() throws PageException {
        public void doProcessBeforeOutput() throws PageException {
          this.setJspName("testDBv5.jsp");
    //testing purpose
      public static void main (String[] arg){
         testDBv5DynPage ef = new testDBv5DynPage();
               ef.doInitialization();
    Thanks Loads
    Quatre

Maybe you are looking for