Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@abatkin
Created February 15, 2013 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abatkin/4960322 to your computer and use it in GitHub Desktop.
Save abatkin/4960322 to your computer and use it in GitHub Desktop.
School class with hashCode() and equals() From a challenge at http://beust.com/weblog/2013/02/13/coding-challenge-light-edition/
/*
* A few assumptions:
* * School is immutable (otherwise, implementing hashCode/equals doesn't really make sense)
* * The problem is incompletely specified, with respect to how to handle missing values:
* * What do you do when both name and nickname are null?
* * What if one School has a name + nickname and the other has just a name, but the names match?
* My decision (and I think this is reasonable) is: Both must match. If a value is null in one,
* it must be null in the other to be considered equal
*/
class School {
private String name;
private String nickname;
private boolean stringsEqual(String one, String two) {
if (one == null) {
if (two == null) {
return true;
} else {
return false;
}
} else {
return one.equals(two);
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof School)) {
return false;
}
School os = (School)o;
return stringsEqual(this.name, os.name) && stringsEqual(this.nickname, os.nickname);
}
@Override
public int hashCode() {
if (name != null) {
if (nickname != null) {
return (name + nickname).hashCode();
} else {
return name.hashCode();
}
} else {
if (nickname != null) {
return nickname.hashCode();
} else {
return 0;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment