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.
will hashcode method will be called whenever my instance variables modified ?.
when hashcode changes , will object recreated newly in heap and new reference will be created or what will be the sideeffect when hashcode chages ?.
How default implementation of hashcode of Object returns same hashcode ?