class People {
private String name;
private int age; public People(int age, String name) {
super();
this.age = age;
this.name = name;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
} public static void main(String[] args) {
People p1 = new People(16, "张三");
People p2 = new People(16, "张三"); System.out.println(p1);
System.out.println(p2);
System.out.println(p1==p2);
}
}==不是比较的是引用地址么,打印出来的地址是一样的,为何p1==p2返回false呢
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
而默认情况下hashCode方式是native,jvm会使用内存地址作为hashCode以保证每个对象的唯一性.现在你覆盖了hashCode,在name,age一样的情况下自然hasCode是一样的,但是这个时候hashCode已经和内存地址没关系了.把toString也改写一下就行了. public String toString() {
return getClass().getName() + "@" + Integer.toHexString(super.hashCode());
}
然后再用name的字段的equals方法比较如果名字相等来判断
System.out.println(p1);
打印的不是P1的地址是打印的应该是p1.tostring()的值.
p1==p2都是false。System.out.println(p1);
也就是System.out.println(p1.toString());而p1.toString()是一个字符串。System.out.println(p1==p2);
可以理解为
String s1 = p1.toString();
String s2 = p2.toString();
而
s1 == s2,肯定是false。如果随便改改hasCode,和toString方法,就让两个对象占用了一个地址空间,那不是乱了。
系统中所有对象都占用一个地址,怎么可能出现这种情况呢?