2

i have following code in my class:

public class Subclass<T> extends Superclass<T> {
//...

@Override
public boolean equals(Object obj) {
    if (obj instanceof Subclass) {
        return str.equals(((Subclass<?>) obj).getStr());
    }
    if (obj instanceof Identity) {
        return str.equals(((Subclass<?>) obj).getStr());
    }
    return false;
}
}

my superclass:

 public class Superclass<T> {
 @NotNull
 String str;

 @Override
 public boolean equals(Object obj) {
    if (obj instanceof Identity) {
        return str.equals(((Identity<?>) obj).getStr());
    }
    return false;
 }

 @Override
 public int hashCode() {
    return str.hashCode();
 }

and checkstyle warns me Definition of 'equals()' without corresponding definition of 'hashCode()'. do i have to override hashcode() in my subclass even thou i dont need it anywhere or is there a better solution to get rid of this warning?

Akka Jaworek
  • 1,970
  • 4
  • 21
  • 47
  • 1
    it´s not 100% necessary, but it´s still better to allways do so.The generell contract says, that if two objects are logical equal they should also produce the same hasCode. [see this question](http://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java) – SomeJavaGuy Aug 30 '16 at 08:50
  • Do you know Lombok? – David Pérez Cabrera Aug 30 '16 at 08:50
  • 1
    As long as you don't use the Subclass in any Hash-classes (``HashSet``, ``HashMap`` etc), you don't need it. Depends on how seriously you take the word 'contract'. – f1sh Aug 30 '16 at 08:52
  • @DavidPérezCabrera yes, everthing is generated here with lombok however i need to override ``equals`` manually. – Akka Jaworek Aug 30 '16 at 08:55
  • @f1sh its required from my code to not have any checkstyle warnings – Akka Jaworek Aug 30 '16 at 08:55
  • 1
    @f1sh "As long as you don't use the Subclass in any Hash-classes..." and all of the classes you do use are contractually forbidden from using hash-based storage of those `Subclass` internally. You (almost certainly) can't know for definite that `Subclass` instances won't be put into hash-based storage now or at some time in the future; so it is a sensible defensive strategy to implement it now. – Andy Turner Aug 30 '16 at 08:57
  • @AndyTurner thank you, this ensured me to implement it – Akka Jaworek Aug 30 '16 at 09:04
  • 1
    @AkkaJaworek you should also make sure that `str` is `final` (along with any other fields you use to compute the hash code), because updates to those fields after insertion into a `HashMap` etc do not cause an update to the map. Basically, your instances can get "lost" in the map, in the sense that they will not necessarily be returned by `map.get`. – Andy Turner Aug 30 '16 at 09:07
  • @AndyTurner completely correct. It just seems that this problem is happening on a very small scale. – f1sh Aug 30 '16 at 10:59

0 Answers0