I use eclipse to automatically generate equals and hashcode for me. First few line of the equals method is as written:
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
I'm having problems with if (!super.equals(obj)). What is this for anyway?
I created a code that illustrates the probem I'm having:
package com.buddy.web;
public class
Test {
public static void main(
String[] args) {
Dalmatian dalmatian = new Dalmatian();
Dalmatian dalmatian2 = new Dalmatian();
System.out.println(dalmatian.equals(dalmatian2));
}
// Dog will always, always have dogName, no exceptions
static class Dog {
public String dogName;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((dogName == null) ? 0 : dogName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
return this.dogName.equals(((Dog) (obj)).dogName);
}
}
// Dalmatian can have dogName null
static class Dalmatian extends Dog {
String dalmatianName;
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((dalmatianName == null) ? 0 : dalmatianName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
final Dalmatian other = (Dalmatian) obj;
if (dalmatianName == null) {
if (other.dalmatianName != null)
return false;
} else if (!dalmatianName.equals(other.dalmatianName))
return false;
return true;
}
}
}
If you run the code above it would result in null pointer exception. Would someone know what if (!super.equals(obj)) is for as I'm considering deleting that line. Thank you