Skip to content

Commit 9d1a503

Browse files
author
jsquared21
committed
Add Ex_27.09
1 parent 73ddcf1 commit 9d1a503

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/*********************************************************************************
2+
* (Implement hashCode for string) Write a method that returns a hash code for *
3+
* string using the approach described in Section 27.3.2 with b value 31. The *
4+
* function header is as follows: *
5+
* *
6+
* public static int hashCodeForString(String s) *
7+
*********************************************************************************/
8+
public class Exercise_27_09 {
9+
public static void main(String[] args) {
10+
11+
}
12+
}
1.09 KB
Binary file not shown.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*********************************************************************************
2+
* (Implement hashCode for string) Write a method that returns a hash code for *
3+
* string using the approach described in Section 27.3.2 with b value 31. The *
4+
* function header is as follows: *
5+
* *
6+
* public static int hashCodeForString(String s) *
7+
*********************************************************************************/
8+
public class Exercise_27_09 {
9+
public static void main(String[] args) {
10+
// Create a list if string
11+
String[] list = {"Mark", "Smith", "tops", "pots", "tod", "dot"};
12+
13+
// Print the hash code for each string
14+
for (String e : list) {
15+
System.out.println("The hash code for \"" + e +
16+
"\" is " + hashCodeForString(e));
17+
}
18+
19+
}
20+
21+
/** Retrun the hash code for string */
22+
public static int hashCodeForString(String s) {
23+
int b = 31;
24+
int hashCode = 0;
25+
for (int i = 0; i < s.length(); i++) {
26+
hashCode = b * hashCode + (int)s.charAt(i);
27+
}
28+
return hashCode;
29+
}
30+
}

0 commit comments

Comments
 (0)