当然不是了,hashCode和equals方法都可以被重写的,如果重写了其中的一个,而没有重写另外一个, 这个结论明显是错误的。
代码如下:
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Test2 t = new Test2("zhangsan", 20); Test2 t2 = new Test2("zhangsan", 30); System.out.println(t.equals(t2)); System.out.println(t.hashCode() == t2.hashCode()); } } class Test2 { public Test2(String name, int age) { super(); this.name = name; this.age = age; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Test2 other = (Test2) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } String name = ""; int age; }
运行结果如下:
true false
当然,我们在重写equals方法时最好将hashCode方法也重写了,代码如下:
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Test2 t = new Test2("zhangsan", 20); Test2 t2 = new Test2("zhangsan", 30); System.out.println(t.equals(t2)); System.out.println(t.hashCode() == t2.hashCode()); } } class Test2 { public Test2(String name, int age) { super(); this.name = name; this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Test2 other = (Test2) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } String name = ""; int age; }
这样的话,题目的答案当然是对的。