(PRIMARY KEY class)what is the necessity to write hashcode


EJB design: (PRIMARY KEY class)what is the necessity to write hashcode

  1. what is the necessity to write hash code and equals methods in the primary key class.the necessity for the existence of this class is toprovide a convinient mapping to the underlying database then why should we write these methods in it.
    thnx in advance ,
  2. may be because the container save primary key in data structure like Hashtable (for fastest access) where you need to overide hashCode() and equals()
  3. Hi,
      I guess the need for overriding the "equals" method in the Primary key class would be to ensure that 2 primary key objects point to the same entity bean. If the normal Object.equals() operation is done, the 2 objects would be considered the same, only if the point to the same primary key object instance. However, there could be 2 different primary key objects for the same entity bean, and hence, semantically, they should be considered as equal , and hence you will have to over-ride the equals method.
       Well, regarding the hashCode method, I don't have any clues. Any ideas would be appreciated !!
  4. Hi KT
    The reason for overwriting the equals() method was pointed out by Sunil.
    Let me try to reason out the overwritting of hashcode()method.
    According to the API docs of "Object" class

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

    But if you have overwritten the equals() method and not the hashcode() method, calling the hashcode() method on each object of same class will produce different integer value.

    To avoid this, we have to overwrite the hashcode() method so that the method on different object of same class return the same integer .

    you can try out this example if you want..

    public class Test {
    int i;
    public Test(int i) { this.i = i; }
    public int hashCode() { return i; }
    public boolean equals(Object o)
    if(o instanceof Test && ((Test)o).i == this.i)
    { return true; }
    { return false; }
    public static void main(String[] args)
    Test test1 = new Test(100);
    Test test2 = new Test(100);
    System.out.println("test1.equals(test2): " + test1.equals(test2));
    System.out.println("test1 hashcode is: " + test1.hashCode());
    System.out.println("test2 hashcode is: " + test2.hashCode());

    Try this example with commenting the hashcode() method .
    Then try uncommentin that.
    You can realise the result.Hope this answers your question.

  5. vijay & sunil ,
      kalakkuringa da
  6. Hi, I was wondering what if we dont override the equals and/or hashcode in the Primary Key Class. Will this give a deploy time exception from the ejb container? When does container actually looks at the implementation details of the Primary Key Class ? Thanks Prabhat Jha