当然不是了,hashCode和equals方法都可以被重写的,如果重写了其中的一个,而没有重写另外一个, 这个结论明显是错误的。
代码如下:
- 1. public class Test {
- 2. public static void main(String[] args) {
- 3. // TODO Auto-generated method stub
- 4. Test2 t = new Test2("zhangsan", 20);
- 5. Test2 t2 = new Test2("zhangsan", 30);
- 6.
- 7. System.out.println(t.equals(t2));
- 8. System.out.println(t.hashCode() == t2.hashCode());
- 9. }
- 10. }
- 11.
- 12. class Test2 {
- 13. public Test2(String name, int age) {
- 14. super();
- 15. this.name = name;
- 16. this.age = age;
- 17. }
- 18.
- 19. @Override
- 20. public boolean equals(Object obj) {
- 21. if (this == obj)
- 22. return true;
- 23. if (obj == null)
- 24. return false;
- 25. if (getClass() != obj.getClass())
- 26. return false;
- 27. Test2 other = (Test2) obj;
- 28. if (name == null) {
- 29. if (other.name != null)
- 30. return false;
- 31. } else if (!name.equals(other.name))
- 32. return false;
- 33. return true;
- 34. }
- 35.
- 36. String name = "";
- 37. int age;
- 38.
- 39. }
运行结果如下:
- 1. true
- 2. false
当然,我们在重写equals方法时最好将hashCode方法也重写了,代码如下:
- 1. public class Test {
- 2. public static void main(String[] args) {
- 3. // TODO Auto-generated method stub
- 4. Test2 t = new Test2("zhangsan", 20);
- 5. Test2 t2 = new Test2("zhangsan", 30);
- 6.
- 7. System.out.println(t.equals(t2));
- 8. System.out.println(t.hashCode() == t2.hashCode());
- 9. }
- 10. }
- 11.
- 12. class Test2 {
- 13. public Test2(String name, int age) {
- 14. super();
- 15. this.name = name;
- 16. this.age = age;
- 17. }
- 18.
- 19. @Override
- 20. public int hashCode() {
- 21. final int prime = 31;
- 22. int result = 1;
- 23. result = prime * result + ((name == null) ? 0 : name.hashCode());
- 24. return result;
- 25. }
- 26.
- 27. @Override
- 28. public boolean equals(Object obj) {
- 29. if (this == obj)
- 30. return true;
- 31. if (obj == null)
- 32. return false;
- 33. if (getClass() != obj.getClass())
- 34. return false;
- 35. Test2 other = (Test2) obj;
- 36. if (name == null) {
- 37. if (other.name != null)
- 38. return false;
- 39. } else if (!name.equals(other.name))
- 40. return false;
- 41. return true;
- 42. }
- 43.
- 44. String name = "";
- 45. int age;
- 46.
- 47. }
这样的话,题目的答案当然是对的。