0

hi guys i have a little problem here to solve.

I have created an equals() method which is only based on the class of the object so that if two obj are of the same class the obj1.equals(obj2) return true. now my question is, How do i implement a hashcode() based only on the obj Class ??

@Override
public boolean equals(Object obj){
    if(obj.getClass() == this.getClass()){
        return true;
    }else{
        return false;
    }
}
3
  • 2
    return 79658765; (for example: any integer would do). Why are you doing that? That seems like a terrible idea. Commented May 14, 2017 at 8:19
  • You can return hashcode of full class name. But Why you are writing such terrible equals method ? Please elaborate more. Commented May 14, 2017 at 8:20
  • What's the use case for this? It seems like something that will blow up in your face... Commented May 14, 2017 at 8:23

1 Answer 1

1

You could return the hashCode of the Class instance:

public int hashCode ()
{
    return getClass().hashCode();
}

This would ensure that two objects which are equal based on your equals() implementation would have the same hashCode().

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.