Introduction
Hasher.java
contains a Functional Interface
and a Concrete Class
.
Take some time to familiarize yourself with the following topics:
The make()
method in the Hasher
class returns an instance of an object that has a
single abstract method, hash()
. There are three distinct ways you can implement this:
-
An inner class
-
An anonymous inner class
-
A lambda expression
The following image demonstrates all three ways with a hash function that you are not implementing in this assignment:
-
case "NAMED"
returns an instance of an inner class,AddAndXOR
which implements thehash()
function. -
case ANONYMOUS
defines and returns a single object that implements thehash()
function using an anonymous inner class. -
case LAMBDA
defines and return a single object that implements thehash()
function using a lambda expression.
All three implementations ultimately have the same end result.
Directions
The four implementations of the hashing algorithm are specified by a String
parameter to Hasher.make(String type)
.
The four algorithms are:
-
FIRST
: specifies a hashing function that returns the ASCII value of the first character of the string. This is not a very effective hashing function! -
SUM
: specifies a hashing function that returns the sum of the ASCII values of all characters in the string. This is better but still not very effective. -
PRIME
: specifies a hashing function that returns a value computed as follows. Initialize the hash code to 7, then iterate the string from start to end, multiplying the previous value of the hash code by 31 and adding the ASCII value of the current character. -
JAVA
: specifies a hashing function that returns the hashCode value from Java, i.e. just callString.hashCode()
.
Warning
|
the hash code may overflow the maximum integer in Java, and thus end up negative.
For this reason you should always call Math.abs on the hash code before returning it.
|
Complete each algorithm for computing the hash code and test them using the main()
method in Hasher.java
.
-
Run
java Hasher
with no parameters and the program will print a usage message. -
Then run again specifying the hashing algorithm and the string to hash.
Note
|
Java has the wonderful capability of being able to specify a main() function for every class,
so many developers choose to write test code directly in the class.
|