版权声明:转载请注明出处。 https://blog.csdn.net/bagpiping/article/details/84314666
1、Object的hashCode( )
public class Object{
public native int hashCode();
}
大家看到了,爸爸类Object提供了一个本地方法,返回值类型为int,奋斗过程交给了儿子类。
2、String类的hashCode( )
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
hash = h = isLatin1() ? StringLatin1.hashCode(value) : StringUTF16.hashCode(value);
}
return h;
}
private boolean isLatin1() {
return COMPACT_STRINGS && coder == LATIN1;
}
再看,String类hashCode方法居然想返回哈希码(hash)!那些看不懂从哪里来的词都是String内部的变量和方法。经过一系列的*&&%%^以后,hashCode返回哈希码,作用是什么?以后写集合框架的时候再说。
3、Integer类的hashCode( ),数值型类以它为例。
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
大家看到了,Integer不仅重写了,还自己重载了,调用Integer的hashCode( )方法直接返回它的int值。比起String来,这个类是真的懒。
4、HashMap类的hashCode( )
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}