C7: Overriding equals and hashCode
CPSC 210
Learning Goals
- Understand why we sometimes need to override equals and hashCode
- Learn how to override equals/hashCode (or use the IDE to help us)
Handling Duplicate Objects
- At the top of every class hierarchy is the Object class
-
Among others, this class defines the following methods
- boolean equals(Object other)
- int hashCode()
- These are used by the contains methods in Java collections
List<Instructor> instructors = new ArrayList<>();
instructors.add(new Instructor("Felix"));
Instructor instructor = new Instructor("Felix");
instructors.contains(instructor);
Handling Duplicate Objects (2)
-
What we need to know about in this course:
- Object class implements a.equals(b) as a == b
- Method can be overridden to change this behavior
- When we override equals we must override hashCode
- if a.equals(b), then
a.hashCode() must equal b.hashCode()
-
We can let IntelliJ help us generate these methods:
- Code > Generate > equals() and hashCode()
Let's ask the docs!
Lecture Ticket Review
public class RecipeBook {
private String name;
private Map<String, List<String>> recipes;
public RecipeBook(String name){
this.name = name;
this.recipes = new HashMap<>();
}
// REQUIRES: recipeName is not already in recipes
// MODIFIES: this
// EFFECTS: adds recipeName to recipes, and assigns an empty list of ingredients
public void addNewRecipe(String recipeName){
List<String> ingredients = new ArrayList<>();
//BLANK 1
}
// REQUIRES: recipeName is in recipes
// MODIFIES: this
// EFFECTS: adds ingredient to recipeName's list of ingredients
public void addToRecipe(String recipeName, String ingredient){
List<String> ingredients = recipes.get(recipeName);
//BLANK 2
}
public void printRecipes(){
System.out.println(this.recipes);
}
}
Lecture Lab
C7: Overriding equals and hashCode
The End - Thank You!
C7: Overriding equals and hashCode
By Steven Wolfman
C7: Overriding equals and hashCode
- 246