1

I am having doubt like when hashcode method() will be called for my object. I overrided hashcode method for MessageThread class.

MainActivity.java

        MessageThread messageThread=new MessageThread();

        
        Log.e("hashcode", messageThread.hashCode()+"");
        Messages messages=new Messages();

        messageThread.addMessage(messages);
        Log.e("hashcode after", messageThread.hashCode()+"");
            

MessageThread.java

public class MessageThread {

    List<Messages> messages = new ArrayList<Messages>();

    
    public boolean equals(Object o) 
    {

        if((o instanceof MessageThread )&&(((MessageThread)o).getMessages().size()==this.getMessages().size()))
        {
            return true;
        }
        else
        {
            return false;
        }
    }


    public int hashCode()
    {
        return messages.size();
    }

    public List<Messages> getMessages() {
        return messages;
    }


    public void setMessages(List<Messages> messages) {
        this.messages = messages;
    }

    public void addMessage(Messages message)
    {
        messages.add(message);
    }

}

Messages.Java

public class Messages {

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }   
}

First I tried by overriding the hashcode method in Class MessageThread I got following output. hascode has been changed

05-02 12:51:14.470: hashcode: 0
05-02 12:51:14.470: hashcode after: 1

Then i tried without overriding hascode method in Class MessageThread I got the following output. hashcode not changed

05-02 12:53:35.417: hashcode : 1105906440
05-02 12:53:35.417: hashcode after: 1105906440

I have following questions out of this.

  1. will hashcode method will be called whenever my instance variables modified ?.

  2. when hashcode changes , will object recreated newly in heap and new reference will be created or what will be the sideeffect when hashcode chages ?.

  3. How default implementation of hashcode of Object returns same hashcode ?

Community
  • 1
  • 1
saravanan
  • 5,339
  • 7
  • 45
  • 52
  • Some of your questions can be answered on the [Wikipedia article about Java hashCode()](http://en.wikipedia.org/wiki/Java_hashCode%28%29) – Andrew T. May 02 '14 at 07:58
  • One of the beauties of Java (and also what makes it harder to read) is that thinks don't get called automagically. – Peter Lawrey May 02 '14 at 08:11

2 Answers2

5

I am having doubt like when hashcode method() will be called for my object.

It is not called automatically by the JVM. Rather, it is called by library code (or whatever) according to that code's needs. For example, HashMap calls hashcode an object when it uses the object as a key; e.g. when you do a get, put, remove and so on.

(If you want to observe your hashcode method being called, put the object into a HashSet.)

will hashcode method will be called whenever my instance variables modified ?.

No.

when hashcode changes , will object recreated newly in heap and new reference will be created or what will be the sideeffect when hashcode chages ?.

No new object is created when the hashcode changes.

If your object's hashcode changes while it is uses as a key in a HashMap, (etcetera) that is going to break the invariants of the HashMap (etc). Bad!! That is likely to break the data structure. For example, operations like HashMap.get may return the wrong answer

How default implementation of hashcode of Object returns same hashcode ?

Some special magic. Read these answers to earlier questions:


UPDATE - it seems that you are confused about what a hashcode is and what the hashcode() method does.

  • The hashcode value is just a 32-bit integer.

  • The hashcode() method is just an ordinary method, whose purpose is to calculate the hashcode value.

  • For a hashcode() method to be useful, it needs to conform to a couple of invariants:

    1. If two objects are equal (according to equals(Object)) then their hashcode() methods should return the same value.

    2. If two objects are NOT equal (according to equals(Object)) then the probability that their hashcode() methods should return the same value should be very small.

    3. While an object is in a hashed data structure, its hashcode must not change.

  • It is the responsibility of the programmer to ensure that the invariants above are satisfied. If you fail, your program is likely to be buggy.

  • The JVM does not / cannot do anything to ensure that you don't break the invariants. And it does not / cannot do anything to "fix" it if you mess up.

  • There are no callbacks, no listeners, nothing like that to tell you (or the HashMap) that a key's hashcode has changed.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Then why hashcode() is called when i modify my instance varaible messageThread.addMessage(messages); . But u said it wont be called. – saravanan May 02 '14 at 08:10
  • @saravanan because you return the size of the list. Which is obviously incremented when you add something to it. – Thomas Jungblut May 02 '14 at 08:12
  • @saravanan - The hashcode is changing because you are changing the state that the hashcode is calculated from; i.e. the size of the `messages` list. The hashcode is not changing because you called `hashcode()`, and calling `hashcode()` is not changing the hashcode value. – Stephen C May 02 '14 at 08:19
  • so, hashcode method will be called when the state of variables changes which i used to calculate hashcode . right?, will there be a listener for this. – saravanan May 02 '14 at 08:25
  • @Stephen C : I will come up with questions after i study further about this. thanks for your valuable answer sofar. – saravanan May 02 '14 at 08:40
  • *"hashcode method will be called when the state of variables changes which i used to calculate hashcode . right?,"* Wrong!! *"will there be a listener for this."* No!! See my updated answer. – Stephen C May 02 '14 at 09:20
1

1.Will hashcode method be called whenever my instance variables modified?

HashCode methode is normally called by various Hash Based Collections to sort the objects in specific buckets using the hashcode. This helps in faster retrival of an Object from the collection. There are many ways in which one implements a hashcode method. If your implementation depends on the instance variables it will naturally change when the instance variables are modified. So there are no listeners which will call your hashcode method when the variables change. Although if any API does call your hashcode method the value returned would be different.

2.When hashcode changes , will object recreated newly in heap and new reference will be created or what will be the sideeffect when hashcode chages ?.

Please refer the hashcode contract

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 {@link java.lang.Object#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.

The Sideeffect of an incorrect hashcode implementation is that the object which you added to a hash based collection would get lost if we are not able to generate the same hashcode while retriving the object.

3.How default implementation of hashcode of Object returns same hashcode ? Default HashCode implementation

Community
  • 1
  • 1
Pratik Shelar
  • 3,154
  • 7
  • 31
  • 51