0

I have an abstract class and I wanted to force all the implementations of the class to implement there own equals and hashCode method. The class has just one method which returns a String.

The abstract class is defined like this

public abstract class Type
{
   public abstract String getType();
   public abstract boolean equals(Object other);
   public abstract int hashCode();
}

I have implemented the equals method. Now I am implementing the hashCode method for this class. I have a couple of questions:

1) Is this the right approach to override the == behavior in all implementations of the class.

2) What would be the best way to implement the hashCode method for this class which only has one function that returns a string?

Is this is a duplicate, please point me to the right answer.

Khawar Ali
  • 3,312
  • 2
  • 25
  • 50
  • 1
    Nit: you can't override the `==` behaviour, only the `equals` behaviour. – Andy Turner Nov 01 '16 at 21:15
  • 2
    "What would be the best way" Entirely depends on what you're trying to do. *A* way would be simply to use `return getType().hashCode();`. – Andy Turner Nov 01 '16 at 21:16
  • And `hashCode` is not needed for `equals` behavior. It's needed for `HashMap` and `HashSet` though, so it's always best to implement it if `equals` is implemented. – Andreas Nov 01 '16 at 21:17
  • @Andy and implement `equals()` as `return getType().equals(that.getType());` so it agrees with `hashCode()` – Bohemian Nov 01 '16 at 21:17
  • @Bohemian sure, after the `instanceof` check (and optionally the `this` check). – Andy Turner Nov 01 '16 at 21:18
  • I have already implemented the equals method. The only thing I was concerned about was that there is no non-static fields in the class so return getType().hashCode() seems like the only option for this other than playing with prime numbers. Not sure which approach will be better to take. – Khawar Ali Nov 01 '16 at 21:18
  • @Bohemian Yes that is my implementation of equals with one exception. I have done Objects.equals(getType, that.getType()) instead of getType().equals(that.getType()). Would that be fine or should I change to string comparison? – Khawar Ali Nov 01 '16 at 21:20

0 Answers0