---
title: "HashCode 理解测试"
author: "feigme"
date: "2007-11-01T14:15:04Z"
tags: []
slug: "hashcode"
draft: false
lastmod: "2007-11-01T14:15:04Z"
id: 137283
url: "https://feigme.iteye.com/blog/137283"
---

java 代码

01. public class HashCodeTest {
02. /\**
03. * @throws java.lang.Exception
04. \*/
05. @Before
06. public void setUp() throws Exception {}
07. /\**
08. * @throws java.lang.Exception
09. \*/
10. @After
11. public void tearDown() throws Exception {}
12. @Test
13. public void testHashCode(){
14. String a = new String("AA");
15. String b = a;
16. String c = new String("AA");
17. String d = new String("BB");
18. String e = "AA";
19. String f = "AA";
20. System.out.println("String a hashcode is : "+ a.hashCode());
21. System.out.println("String b hashcode is : "+ b.hashCode());
22. System.out.println("String c hashcode is : "+ c.hashCode());
23. System.out.println("String d hashcode is : "+ d.hashCode());
24. System.out.println("String e hashcode is : "+ e.hashCode());
25. System.out.println("String f hashcode is : "+ f.hashCode());
26. System.out.println("a.equals(b) : "+ a.equals(b));
27. System.out.println("a==b : "+ (a==b));
28. System.out.println("a.equals(c) : "+ a.equals(c));
29. System.out.println("a==c : "+ (a==c));
30. System.out.println("b.equals(c) : "+ b.equals(c));
31. System.out.println("b==c : "+ (b==c));
32. System.out.println("a.equals(e) : "+ a.equals(e));
33. System.out.println("a==e : "+ (a==e));
34. System.out.println("e.equals(f) : "+ e.equals(f));
35. System.out.println("e==f : "+ (e==f));
36. Person p1 = new Person();
37. Person p2 = p1;
38. Person p3 = new Person();
39. System.out.println("Model p1 hashcode is : "+ p1.hashCode());
40. System.out.println("Model p2 hashcode is : "+ p2.hashCode());
41. System.out.println("Model p3 hashcode is : "+ p3.hashCode());
42. System.out.println("p1.equals(p2) : "+ p1.equals(p2));
43. System.out.println("p1==p2 : "+ (p1==p2));
44. System.out.println("p1.equals(p3) : "+ p1.equals(p3));
45. System.out.println("p1==p3 : "+ (p1==p3));
46. System.out.println("p2.equals(p3) : "+ p2.equals(p3));
47. System.out.println("p2==p3 : "+ (p2==p3));
48. }
49. }

打印的结果为：

java 代码

01. String a hashcode is : 2080
02. String b hashcode is : 2080
03. String c hashcode is : 2080
04. String d hashcode is : 2112
05. String e hashcode is : 2080
06. String f hashcode is : 2080
07. a.equals(b) : true
08. a==b : true
09. a.equals(c) : true
10. a==c : false
11. b.equals(c) : true
12. b==c : false
13. a.equals(e) : true
14. a==e : false
15. e.equals(f) : true
16. e==f : true
17. Model p1 hashcode is : 12934710
18. Model p2 hashcode is : 12934710
19. Model p3 hashcode is : 28064776
20. p1.equals(p2) : true
21. p1==p2 : true
22. p1.equals(p3) : false
23. p1==p3 : false
24. p2.equals(p3) : false
25. p2==p3 : false

结论：

待续。。。