class Test
{
public static void main(String[] args)
{
System.out.println(new A().getHashCode());
System.out.println(new A().getHash());
System.out.println(new B().getHashCode());
System.out.println(new B().getHash());
}
};class A
{
public int getHashCode()
{
return super.hashCode();
} public int getHash()
{
return hashCode();
}
};class B
{
public int getHashCode()
{
return super.hashCode();
} public int getHash()
{
return hashCode();
}
};出来的结果是:
14576877
12677476
33263331
6413875请问这里的super.hashCode();是那个对象的hashCode呢?
这里的输出结果的第一行和第三行不是应该相同吗?
恳求大家解析一下
{
public static void main(String[] args)
{
System.out.println(new A().getHashCode());
System.out.println(new A().getHash());
System.out.println(new B().getHashCode());
System.out.println(new B().getHash());
}
};class A
{
public int getHashCode()
{
return super.hashCode();
} public int getHash()
{
return hashCode();
}
};class B
{
public int getHashCode()
{
return super.hashCode();
} public int getHash()
{
return hashCode();
}
};出来的结果是:
14576877
12677476
33263331
6413875请问这里的super.hashCode();是那个对象的hashCode呢?
这里的输出结果的第一行和第三行不是应该相同吗?
恳求大家解析一下
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count; for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
具体的方法是这样的
public boolean equals(Object obj) {
return (this == obj);
} 所以这是对两个对象的地址值进行的比较(即比较引用是否相同)。
但是你也要知道对一些封装类Math,Integer,Double。。使用equals()方法时,已经覆盖了object类的equals()方法
。比如string类中
比如在String类中如下:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
所以基本类型是进行值的比较
3:总的理解是
equals()相等的两个对象,hashcode()一定相等;
equals()不相等的两个对象,却并不能证明他们的hashcode()不相等。
equals()方法不相等的两个对象,hashcode()有可能相等。
反过来:hashcode()不等,一定能推出equals()也不等;hashcode()相等,equals()可能相等,也可能不等。
而hashcode的值是46792755......这里内存中的地址和hashcode的值,之间有什么联系吗?