ITeye博客

HashCode 理解测试

feigme · 2007-11-01 14:15 · Java · Markdown

java 代码

  1. public class HashCodeTest {
  2. /**
  3. * @throws java.lang.Exception
  4. */
  5. @Before
  6. public void setUp() throws Exception {}
  7. /**
  8. * @throws java.lang.Exception
  9. */
  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 代码

  1. String a hashcode is : 2080
  2. String b hashcode is : 2080
  3. String c hashcode is : 2080
  4. String d hashcode is : 2112
  5. String e hashcode is : 2080
  6. String f hashcode is : 2080
  7. a.equals(b) : true
  8. a==b : true
  9. 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

结论:

待续。。。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。