Quidditch – Part 3
Prerequisite: You finished the lesson: HashMap
.
Goal: set up the Game class
.
Task 1
scoreboard
implies parity between Team
and Integer
. Define a HashMap
that can store Team
: Integer
entries.
Task 2
-
Constructor.
-
Two parameters:
Team home
,Team away
. -
Sets
scoreboard
equal to a new object of theHashMap class
. -
Adds
home
:0
andaway
:0
to the scoreboard.
-
-
Getter:
getScore
-
Receives one parameter:
Team team
. -
Returns the score for the requested
team
.
-
-
Setter:
setScore
-
Receives two parameters:
Team team
,Integer Score
. -
Updates a
team
's score to 50.
-
-
Getter:
getTeam
.- Receives one parameter:
String name
. return null
for now.
- Receives one parameter:
-
Setter:
setTeam
- Impossible
- You cannot update a key.
Task 4
1. Test the constructor
Inside main()
, create a new object of the Game
class. Pass the following objects into the constructor.
home = new Team("GRYFFINDOR", "Oliver", "Harry", new String[] {"Angelina", "Ginny", "Katie"}); away = new Team("SLYTHERIN", "Vincent", "Draco", new String[] {"Bridget", "Harper", "Malcolm"});
Compare your output with one of the following scenarios:
- Reference Trap: each key shares the same reference as the outside variable.
- Pitfall: updating the outside variable updates the key in the
HashMap
- Pitfall: updating the outside variable updates the key in the
- Correct Result: each key should store a unique reference that points to a copy.
2. getScore
From main()
, fetch the score for gryffindor
and print it. If you did everything correctly, it should not work and return null
.
3. setScore
From main()
, update the score for gryffindor
to 50
. If you did everything correctly, it should not work. It should add a new key to the HashMap
instead. Use breakpoints to confirm your result.
Task 5: equals
Your code is using the default equals
method to compare Team
objects.
-
Problem: The default
equals
method compares references. But, each key has a different reference from the one being passed in.-
getScore
: It can't find a reference that matches the parameter, so it returnsnull
. -
setScore
: It can't find a reference that matches the parameter. So, it adds a new key instead of updating the existing one.
-
-
Solution: The code needs your
equals
method to compareTeam
objects. Hint: arrays are equal if they share the sametoString
.
After creating your equals()
method, re-launch the
debugger.
The code should still not work!
What's wrong?
Adding an equals()
method is not enough. You also need to add a hashCode()
method.