Created
September 29, 2014 02:55
-
-
Save EmmanuelOga/7bb8767d39950c7d3282 to your computer and use it in GitHub Desktop.
Equals / HashCode / ToString template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Objects; | |
/* | |
* When defining equals, hashCode should be defined too. | |
* It is the civil thing to define toString too. | |
*/ | |
class Base { | |
public String a = "a"; | |
@Override | |
public boolean equals(Object obj) { | |
if (obj == null) { return false; } | |
if (obj == this) { return true; } | |
if (getClass() != obj.getClass()) { return false; } | |
Base other = (Base) obj; | |
return Objects.equals(this.a, other.a); | |
} | |
@Override | |
public int hashCode() { | |
return Objects.hash(this.a); | |
} | |
@Override | |
public String toString() { | |
return getClass().getName() + "[a=" + a + "]"; | |
} | |
} | |
class Super extends Base { | |
public String b = "b"; | |
@Override | |
public boolean equals(Object obj) { | |
if (! super.equals(obj)) { return false; } | |
Super other = (Super) obj; | |
return Objects.equals(this.b, other.b); | |
} | |
@Override | |
public int hashCode() { | |
return Objects.hash(super.hashCode(), this.b); | |
} | |
@Override | |
public String toString() { | |
return super.toString() + "[b=" + b + "]"; | |
} | |
} | |
public class Sandbox { | |
public static void main(String[] args) { | |
Base b = new Base(); | |
Super s = new Super(); | |
System.out.println(b); | |
System.out.println(s); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment