重写hashcode(hashcode是hash函数计算出的值):重写hashcode方法不止要重写基本数据类型的hashcode方法,如果重写hashcode方法是用到了对象类型,那么该对象类型也必须要重写hashcode方法,否则每次得到的hashcode值不一定一致,那么重写hashcode方法的意义就不大了;
class bean{
int x;
String string;
@Override
public int hashCode() {
final int prime = 31;
/*这里面为啥用个31来计算,而且很多人都是这么写的,
这是因为31是个神奇的数字,任何数n*31都可以被jvm优化为(n<<5)-n,
移位和减法的操作效率比乘法的操作效率高很多!*/
int result = 1;
result = prime * result + ((string == null) ? 0 : string.hashCode());
//当这个域的值为null的时候(即 string == null 时),那么hashCode值为0
result = prime * result + x;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
bean other = (be