Quidditch – Part 4
Prerequisite: You finished the lesson: hashCode()
.
Background
equal
objects must share the samehashCode
.
When you add an equals()
method, you must also add a hashCode()
method that assigns equal objects the same hashCode.
HashMap
uses thehashCode
to find which bucket the key is in.- After it finds the bucket,
equals()
can compare your object against the key.
Task 1
Inside Team.java
, add a hashCode
method that assigns equal objects the same hashCode
.
NOTE: Objects.hash()
doesn't work with arrays. Pass the chasers
field in as a String
: Arrays.toString(chasers)
.
Task 2: Test your code
Expected Output:
getScore
should return the score 0.setScore
should update gryffindor's score.
Task 3: getTeam
You will retrieve the Team
key that matches the String
parameter.
Background information:
- You can run through
key-value
pairs as anentrySet
. forEach
runs through every entry.- Each entry contains a key and value.
- You can also run through each
key
as akeySet
.
Task: Choose to run an entrySet
or keySet
through a stream pipeline. Then, choose one of the following pipelines to return the matching key:
Pipeline 1
Pipeline 2
There are four possible ways to approach this problem. Only do one. The solution video will cover all four implementations.
Hints:
- For
entrySet
, the stream is a sequence of entries. - For
keySet
, the stream is a sequence of keys. - For pipeline 2, collect should return a list with only one element.
- Indexing a
List
is the same asArrayList
.
4. Test
From main()
, fetch the object named "GRYFFINDOR"
. Then, print the object that it returns.
Task 4: gameCount
Create a static
variable called gameCount
that counts up every time there's a new Game
.