When we override Hashcode and Equal Methods

Hi....I have doubt regading Hashcode and equal methods
why we override this two methods....
why we override hashcode method when we are overriding equal method,
i would very thankful to give answser
Thank you
Ramesh

hash code is computed to check the equality of two
objects ,
that is why if u change the default equal method
implementation , u need to change the hashcode method
as well.That's an incomplete answer at best.
The hashcode method is used by hashing algorithms and data strcutures such as HashMap. This value is used to determine what 'bucket' the reference will go into. It cannot, by itself determine equality.
If you are still unsure, I suggest looking up 'hash table' on google. I'm sure there's a decent explanation on wikipedia.

Similar Messages

  • Help need to know hashcode() and Equals method

    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........

    jverd wrote:
    euph wrote:
    jverd wrote:
    euph wrote:
    REFTY5_ wrote:
    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........Thery're asking you to override the equals and hashCode methods. Override means replace.So does "overwrite." However, as you point out, "override" is the correct word here.So you think "overwrite" means the same as "replace"?To the same extent that "override" does. But both are in the general sense. Override has a specific meaning in this Java context, and overwrite does not.Don't tell me. That's what I said in my original reply.
    To my ear it doesn't. To me "overwrite" means the original is destroyed, whereas when something is "replaced" the fate of the original is unknown. So I think there's a slight semantic difference between these words.Fair enough.Fair enougth, but the next time I suggest you're better sorted.

  • Use of hashCode and equals method in java(Object class)

    What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.

    You could find that out easily with google, that is a standard junior developer interview question.

  • Why do we need to override Hascode and Equals method?

    Hi,
    == checks if the two references are equal and .equlas will check if the value is same, if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).
    Please someone elaborate on this and also tell me what role hashcode plays in this.
    thanks
    Anirudh

    anirudh1983 wrote:
    if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).Many equals() methods do run an '==' check first for efficiency (and I would recommend it if you're writing one yourself).
    Please someone elaborate on this and also tell me what role hashcode plays in this.The reason that it is good practise to override equals() and hashCode() together is to maintain consistency.
    Hashcodes are used by all Java collections that contain the word 'Hash' in their name, and may also be used by other programs that need a hash code for identification; so if you supply one, you must follow the rules (which you can find in the API for Object.equals() and Object.hashCode()).
    The main rule is this: *objects that are equal() must have equal hashcodes*.
    Note that the reverse is NOT true: objects that are not equal() do not have to have different hashcodes, but it is usually better if they do.
    There is quite a lot to know about hashcodes, and what makes a good one, so I suggest you follow dcminter's advice if you want to be a happy and prosperous Java programmer.
    Winston

  • Do I need to override enum's hashCode() and equals()?

    Hi all:
    I have a enum type let's say it is
    public enum Type
      ONE,
      TWO;
    }If I want to compare the enum value to see if they are same value or not, let's say I have two:
    Type a = Type.ONE;
    Type b = Type.TWO;should I use a.equals(b) or (a == b) If I want to use it as another class's key field, and I want to override this class hashCode() and equals() methods.
    Can enum Type return the correctly hash code?
    For example the class is like:
    public Class A
      Type type;
      pubilc boolean equals(Object other)
        // here skip check class type, null and class cast
        if(other.type.equals(this.type))
           return true;
        else
         return false;
      public int hashCode()
        int result = 31;
        result += 31 * result + type.hashCode() ;
       // can we get correct hash code from enum here?
        return result;
    }

    Answered by the test code by myself.
    We can use either equals or (==) to see if they are the same value.
    The enum's hashCode() use System.identityHashCode() to generate the hashCode and they are always correct

  • Method Overriding-toString(),hashCode() and equals()?

    Hi,
    In some Java Classes, I saw that
    toString()
    hashCode()
    equals()
    these 3 methods of Object Class is overloaded.
    I don't understand why and in what situation we have to override these 3 methods of Object Class.
    Thanks in advance for ur Knowledge Sharing.
    Regards,
    S.Prabu

    toString() is typically overridden in subclasses so as to output something useful about a class like instance variable values instead of just a hashvalue representing the object reference as per Object.
    hashCode() and equals() are overridden typically for use within the collections framework though you need to fully understand the hashing contract before starting to override these as they can cause strange results if not overridden correctly.
    Take a look at collections and specifically the hashing functionality of HashMap and HashSet for more info on these.

  • Scenario in which implement or Write our own hascode and equals method

    Dear All,
    Please let me know in which circumstances we write our own Hashcode method and equals method not the default one provided by java.Kindly give me complete code and scenario.
    Thanks
    Sumit

    Thanks for your reply
    I have one more question.
    When equal method of Object class give the same result as equals we override then why should we override equals.For example see the below code
    public class EqualsTest{
    public EqualsTest() {
         super();
    public static void main(String[] args) {
    Moof one =new Moof(8);
    Moof two =new Moof(8);
    if(one.equals(two))
    System.out.println("one is equals to two");
    class Moof {
    private int moofvalue;
    Moof(int val){
    System.out.println("val inside moof constructor"+val);
    moofvalue=val;
    System.out.println("moofvalue inside moof constructor" +moofvalue);
    public int getMoofValue()
    System.out.println("moofvalue inside getmoffvalue method "+moofvalue);
    return moofvalue;
    public boolean equals(Object o)
    System.out.println("Object o in equals"+o);
    if( (o instanceof Moof) &&(( (Moof)o).getMoofValue()==this.moofvalue))
    System.out.println("true");
    return true;
    else
    System.out.println("false");
    return false;
    Here the output we get is :
    val inside moof constructor8
    moofvalue inside moof constructor8
    val inside moof constructor8
    moofvalue inside moof constructor8
    Object o in equalsMoof@119c082
    moofvalue inside getmoffvalue method 8
    true
    one is equals to two
    The last output "one is equals to two" gives the same result as overridng equals by us.So why should we override equals here.
    Thanks
    Sumit

  • ToString array and equals method

    I have an array and i need to get the toString to output the information. How do I get that to happen. This is what i ahve so far.
       public String toString(){
              //should indicate all cities
              System.out.print("Cities :");
              for (int i = 0; i < cities.length -1; i++)
                   return cities;
    Here is another piece of code I am finishing. Please tell me if the loop and equals method is correct but what is the value to return?
       public City getCity(String cityName){
              //returns the City with name cityName (must search for city in the array)
              //if the city does not exist, it returns null
              for(int i = 0; i < cities.length; i++)
                   if(cityName.equals ("cityName"))
                        return ;
                    else return null;
                Message was edited by:
    ehj3000

    great my world class is fixed now im getting missing return statements on the two methods
           public City getCity (String cityName){
          //returns the City with name cityName (must search for city in the array)
          //if the city does not exist, it returns null
             for(int i = 0; i < cities.length; i++)
                if(cities.getName().equals(cityName))
    return cities[i];
    else
    return null;
    public String toString(){
    //should indicate all cities
    System.out.println("Cities: ");
    for (int i = 0; i < cities.length -1; i++)
    return cities[i].getName();

  • SCJP 5.0 A question about hashcode() and equals()

    Here's an exercise from a book.
    Given:
    class SortOf {
    String name;
    int bal;
    String code;
    short rate;
    public int hashCode() {
    return (code.length()*bal);
    public boolean equals(Object o) {
    //insert code here
    Which of the following will fulfill the equals() and hashCode() contracts for this
    class? (Choose all that apply)
    A return ((SortOf)o).bal == this.bal;
    B return ((SortOf)o).code.length() == this.code.length();
    C return ((SortOf)o).code.length()*((SortOf)o).bal == this.code.length()*this.bal;
    D return ((SortOf)o).code.length()*((SortOf)o).bal*((SortOf)o).rate ==
    this.code.length()*this.bal*this.rate;
    C is a correct answer but D is also a correct answer according to the book writer,
    and I don't understand why.
    Normally, the rule is that if two objects are equals (according to the equals
    method)) then they must return the same hashcode. If we have two objects A and B;
    and A.bal == 2, A.code.length()==3, A.rate == 4 and B.bal == 4, B.code.length() ==
    3 and B.rate == 2. A and B are equals according with the D answer but they do not
    return the same hashcode.
    May someone help me make it clear?

    Generally ,the instance members decides the equals( ) & hashCode( ) contract . Here the code.length , bal fields are generating the hashCode.
    So it is appropriate to override the equals( ) method in such a way that , thonly those two fields wil decid the equality of the objects .
    Thanks,
    laksh.

  • Implementing hashcode and equals

    Is there anything more than performance reasons to always implement hashCode when you implement equals? If I understand correctly, when you put items in a hashtable it chooses the bucket by the hashcode and checks there is no equal item with the equals method. So it should still work if you never implement the hashcode method. But is there any other reason to implement hashCode than performance? Or have I just understood this completely wrong?

    Everything you say is true. And your example shows that point well. However, what if I just implement a hashCode that always returns 0? How will this work then? And does it have any differences than performance?
    Here is an example
    import junit.framework.*;
    import java.util.*;
    public class EqualsTest extends TestCase
      public void testHashCode()
        Map hashTable = new Hashtable();
        hashTable.put( new TestItem( 0 ), "0" );
        hashTable.put( new TestItem( 1 ), "1" );
        assertEquals( 2, hashTable.size() );
        Set hashSet = new HashSet();
        hashSet.add( new TestItem( 0 ));
        hashSet.add( new TestItem( 1 ) );
        assertEquals( 2, hashSet.size() );
      private class TestItem
        private final int i;
        public TestItem( int i )
          this.i = i;
        public boolean equals( Object o )
          final TestItem testItem = ( TestItem ) o;
          return i == testItem.i;
        public int hashCode()
          return 0;
    [/code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • String equal method Vs Object equal method.

    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.

    RGEO wrote:
    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.Because "equal" means different things for different objects. For a String, "equal" would mean that both Strings being compared have the exact same characters, in the same sequence. For an Integer, "equals" would mean that both objects have the same integer value.

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

  • Implementation of equals, hashCode, and

    I am writing an RMI application where the implementation of the remote interface cannot extend UnicastRemoteObject because it already extends another class. So, I need to explicitly export the server object using UnicastRemoteObject.exportObject(server, 0);� no problem.
    Problem is I�ve read that in order to make the class behave as if it had extend UnicastRemoteObject, you must provide implementations for equals, hashCode, and toString. I�ve searched the world over for implementations of these methods equivalent to those found in UnicastRemoteObject� no luck so far.
    Could you help me out?
    I�ve found some code that I�ve listed below� Is it equivalent to the equals and hashCode method found in UnicastRemoteObject? What about toString()?
    public class RemoteDataServer extends LocalDataServer implements RemoteInterface{
        private Remote serverStub;
        public RemoteDataServer() throws IOException {
            super();
            //export remote object
            serverStub = UnicastRemoteObject.exportObject(this);
        public boolean equals(Object obj) {
            return (obj == this || serverStub.equals(obj));
        public int hashCode() {
            return serverStub.hashCode();
    //toString()???

    Hi,
    At book Effective Java by Joshua Bloch you can see some info
    overriding these members.
    See at http://java.sun.com/docs/books/effective/index.html
    Here is the toString()spec method from Object :
    Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
    The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
    getClass().getName() + '@' + Integer.toHexString(hashCode())
    but toString from class String simply returns the string contents of
    an object.
    Hope this help

  • Overriding hashcode method

    Can u pls tell me friends why should definetly i override the hashcode method if i override equals method of the Object class

    Because the contracts of equals and hashCode are strongly bound to each other.
    For each objects x and y where x.equals(y) returns true x.hashCode() must be equal to y.hashCode().
    If you don't follow this convention you'll get hard-to-find bugs as soon as you use your object as a key in some kind of HashMap/HashTable/...

  • How to override equals method

    The equals method accepts Object as the parameter. When overriding this method we need to downcast the parameter object to the specific. The downcast is not the good idea as it is not the OO. So can anyone please tell me how can we override the equals method without downcasting the parameter object. Thank you.

    For comparing the objects by value overriding the equals method what I did is like this
    public boolean equals(Object o){
        if( o instanceof Book){
            Book b = (Book)o;
            if(this.id == b.id)
                return true;
        return false;
    }But in the above code I have to downcast the object o to the class Book. This downcasting is not a good as it is not Object-Oriented. So what I want to do is avoid the downcasting. So any idea how to do it?

Maybe you are looking for

  • In which table can i add "pdf" as possible type of attachment to WF?

    Hi, Who knows the table name where i could add "pdf" as possible type of attachment to the workflow? In a workflow step i want an agent to create an attachement. When the user clicks the paperclip-icon he/she is presented a small screen, first requir

  • ITunes crashing when trying to open "apps" folder when iPhone is connected.

    When I plug in my iPhone and try to open the "apps" folder, itunes crashes. This problem occurs everytime I try to open the "apps" folder. Please help?

  • Help with installing flash player 9

    alright i have done everything i can find on fixing this but nothing works the registry stuff doesn't do anything some times there is no registry files as the one specified in some post or the can be found or modified something like that and the debu

  • Run bapi_bus2054_create_multi in background

    Hi, I'm able to run this BAPI bapi_bus2054_create_multi in foreground but unable to run in background while creating a session. Can anyone let me know how I can run this bapi in background. Regards, Yahya

  • Unable to import into PSE 7 Organizer

    I've got PSE 7 on a Windows XP- "Fusion" partioned drive running on a Mac OS 10.5. The editor of PSE 7 will open these images from a shared file, but the organizer will not import them from that same shared file. I've tried to import into organizers