Last active
December 14, 2015 10:39
-
-
Save jimwhite/5073867 to your computer and use it in GitHub Desktop.
A tweak to the API gets the School challenge right.
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.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