DESKTOP-F6K5GEP_20200828-崔婧涓
一、问题
hashCode()与identiyhashCode() 有什么区别?
解决
private String type ;
public Birds(String type) {
super();
this.type = type;
}
@Override
public String toString() {
// 通过super调用父类Object的toString方法
System.out.println( super.toString() );
return "Birds[type=" + type + "]";
}
@Override
public int hashCode() {
int hash = super.hashCode();
System.out.println( "object hashcode : " + hash );
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals( Object o ) {
if( o != null ) {
// o instanceof Birds 判断不严谨
// 因为 o 如果是 Birds 子类类型的对象时,o instanceof Birds 也返回true
if( this.getClass() == o.getClass() ) {
Birds b = (Birds)o;
return this.type.equals( b.type ) ;
}
}
return false;
}
测试:
public static void main(String[] args) {
Birds b = null ;
System.out.println( b );// b == null ? "null" : b.toString()
b = new Birds( "候鸟" ); ;
System.out.println( b );
System.out.println( b.hashCode() );
System.out.println( System.identityHashCode( b ) );
}
运行结果:
null
object hashcode : 1562557367
com.itlaobing.hashcode.Birds@a5145
Birds[type=候鸟]
object hashcode : 1562557367
676165
1562557367
得出结论:
hashCode() 是继承了Object重写后的方法,可以改写重写后的hashCode()方法。
identiyhashCode() 是由c和c++编写的来自Object本身的方法,不可以改写。无论子类是否重写hashCode()方法,它都会返回Object默认的哈希码值。
所以用identiyhashCode()比较严谨。
二、吐槽
今天老韩说的内容都很清楚,就是有一点点“啰嗦”,没什么可吐槽的。
近期评论