Skip to content

Instantly share code, notes, and snippets.

@jimwhite
Last active December 14, 2015 10:39
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 jimwhite/5073867 to your computer and use it in GitHub Desktop.
Save jimwhite/5073867 to your computer and use it in GitHub Desktop.
A tweak to the API gets the School challenge right.
import java.util.HashSet;
import java.util.Set;
public class School {
private final String name;
private final String nickname; // Nicks are not unique. How many Aggies are there?
public School(String name, String nickname) {
this.name = name;
this.nickname = nickname;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof School)) return false;
School other = (School) obj;
return name.equals(other.name);
}
public boolean equalsFuzzily(Object obj) {
if (!(obj instanceof School)) return false;
School other = (School) obj;
return name.equalsIgnoreCase(other.name) || nickname.equalsIgnoreCase(other.nickname);
}
@Override
public String toString() {
return name + " (aka " + nickname + ")";
}
public static void main(String[] args)
{
School school1 = new School("University of Pennsylvania", "upenn");
School school2 = new School("University of Pennsylvania", "Penn State");
System.out.println("school1: " + school1);
System.out.println("school2: " + school2);
System.out.println("Equals: " + school1.equals(school2));
System.out.println("EqualsFuzzily: " + school1.equalsFuzzily(school2));
Set<School> schools = new HashSet<School>();
schools.add(school1);
schools.add(school2);
System.out.println("Set: " + schools);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment