Java 为什么String对象的hashCode()与自定义类的hashCode()不同';对象
为什么Java 为什么String对象的hashCode()与自定义类的hashCode()不同';对象,java,Java,为什么stringObject的hashcode是我提供的字符串 String s = new String(); // here the hascode is 0. 但是当我得到我创建的某个对象的哈希代码时 testClass o = new testClass(); // the hashcode is some random number. 我的问题是这两者有什么区别?我的理解是hashCode()来自Object类,它是所有类的母亲 为什么stringObject的哈希代码是我提供
stringObject的hashcode是我提供的字符串
String s = new String(); // here the hascode is 0.
但是当我得到我创建的某个对象的哈希代码时
testClass o = new testClass(); // the hashcode is some random number.
我的问题是这两者有什么区别?我的理解是hashCode()
来自Object
类,它是所有类的母亲
为什么stringObject的哈希代码是我提供的字符串?
例如String s=新字符串(“hello”);//这里的hascode是hello
事实并非如此
hashCode()
是一个整数
您似乎混淆了hashcode()和toString()
如果要检查hashcode()
我想你把hashCode()
和toString()
搞混了
每个对象的默认toString()
实现实际上是@
,数字恰好是对象的十六进制散列码,但是可以(并且应该)被能够提供更有意义的字符串表示的类覆盖。对于一个字符串,最明显的字符串表示就是它本身。string s=newstring(“hello”)此函数的哈希代码永远不会是Hello,因为hashCode()方法返回类型是int而不是字符串字符串
是Java库中提供的类。因此,hashCode()
方法已被此类的创建者重写以反映它。请不要确认hashcode是int值
创建类时,您希望重写hashCode()
和equals()
方法,以便能够比较对象,并执行其他很酷的操作(例如,将它们放在HashMap
中)
您需要注意如何实现hashCode()
,因为您希望遵守一般约定,即如果根据equals()
方法,两个对象相等,则它们具有相同的hashCode()
,而相反的情况不一定一定是正确的(但建议这样做)
你可以在这里找到更深入的解释-这里有一些问题:
正如其他人已经说过的-hashCode()
返回一个整数,您可能会混淆toString()
在我看来,哪个更重要:Object
既有hashCode()
又有toString()
方法。但是,对象
的任何子类都可以使用此方法。调用方法时-将调用动态类型的方法,因此对于String
,将调用String.hashCode()
,而不是Object.hashCode()。这就是所谓的
例如:
public static class A {
public void foo() {
System.out.println("A");
}
}
public static class B extends A{
@Override
public void foo() {
System.out.println("B");
}
}
public static void main(String[] args) throws Exception {
A a = new B();
a.foo();
}
在上面的代码快照中,将调用B.foo()
,并打印B
,因为B
覆盖foo()
,并且a
的动态类型是B
,因此调用B.foo()
在您的例子中:由于String
重写了hashCode()
,因此调用了String.hashCode()
,而对于testClass
,它不会重写hashCode()
,因此原始的对象.hashCode()
被调用。方法始终返回一个整数,该整数是对象的整数。nativ实现在类Object
中可用。如果要创建自己的类型哈希,必须覆盖hashCode()
toString()
将返回对象的字符串表示形式和hashCode()
(如上所述)对象的哈希值
类String
覆盖hashCode()
。这是通过String
实现的:
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
public int hashCode(){
int h=散列;
int len=计数;
如果(h==0&&len>0){
int off=偏移量;
char val[]=值;
对于(int i=0;i
任何类都可以重新定义hashcode。@UmNyobe:但是返回值不能更改,这就是为什么这个问题没有意义。hashcode是一个int,所以我不确定您在哪里看到它是“hello”…我回答的是hashcode()来自对象类,它是所有类的母亲。
这里不需要实例化字符串,只需编写String s=“hello”代码>我已经回答了,请阅读你似乎混淆了hashcode()和toString()不。请看我的问题我刚刚编辑了它我删除了“hello”但为什么hashcode()不是随机数?你是对的,对象声明hashcode(),但实现在String类中不同,String类重写hashcode方法,而您的类则不重写hashcode方法,因此您的类(如果未重写)hashcode将调用对象的默认实现,这就是数字不同的原因,希望此helpsOK现在可以帮助您,谢谢,很抱歉在发布我的问题之前没有检查。@JigarJoshi:答案没有回答编辑过的问题,但评论确实如此。请编辑答案以包含此信息,以便将来的读者也可以使用。
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}