Skip to content

Commit 70955f2

Browse files
committed
HashCodeTest
1 parent 21d2335 commit 70955f2

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package hashcode_test;
2+
3+
import java.util.HashMap;
4+
import java.util.HashSet;
5+
6+
public class HashCodeTest {
7+
public static void main(String[] args) {
8+
int a = 42;
9+
System.out.println(((Integer) a).hashCode());
10+
int b = -42;
11+
System.out.println(((Integer) b).hashCode());
12+
13+
double c = 3.1415926;
14+
System.out.println(((Double) c).hashCode());
15+
16+
String d = "hackfun";
17+
System.out.println(d.hashCode());
18+
19+
Student student = new Student(3, 2, "Hackfun", "jiang");
20+
System.out.println(student.hashCode());
21+
22+
23+
HashSet<Student> set = new HashSet<>();
24+
set.add(student);
25+
26+
HashMap<Student, Integer> scores = new HashMap<>();
27+
scores.put(student, 100);
28+
}
29+
}
30+
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package hashcode_test;
2+
3+
public class Student {
4+
5+
int grade;
6+
int cls;
7+
String firstName;
8+
String lastName;
9+
10+
Student(int grade, int cls, String firstName, String lastName) {
11+
this.grade = grade;
12+
this.cls = cls;
13+
this.firstName = firstName;
14+
this.lastName = lastName;
15+
}
16+
17+
18+
public int hashCode() {
19+
20+
int B = 31;
21+
22+
int hash = 0;
23+
hash = hash * B + grade;
24+
hash = hash * B + cls;
25+
hash = hash * B + firstName.toLowerCase().hashCode(); // 忽略大小写
26+
hash = hash * B + lastName.toLowerCase().hashCode(); // 忽略大小写
27+
// 可能产生溢出,但依然没有关系
28+
29+
return hash;
30+
}
31+
32+
@Override
33+
public boolean equals(Object o) {
34+
if (this == o)
35+
return true;
36+
37+
if (o == null)
38+
return false;
39+
40+
41+
if (!(o instanceof Student) || getClass() != o.getClass())
42+
return false;
43+
44+
Student another = (Student) o;
45+
46+
return this.grade == another.grade &&
47+
this.cls == another.cls &&
48+
this.firstName.toLowerCase().equals(another.firstName.toLowerCase()) &&
49+
this.lastName.toLowerCase().equals(another.lastName.toLowerCase());
50+
}
51+
52+
}

0 commit comments

Comments
 (0)