java实体类中equals和hashCode方法的重写
public class User{
private int id;
private String name;
private int age;
setget方法
@Override
public boolean equals(Object obj) {
if (obj == null){
return false;
}
if (this == obj){
return true;
}
if (obj instanceof User){
User user = (User)obj;
if (user.getId().equals(this.id) && user.getName().equals(this.name) && user.getAge().equals(this.age)){
return true;
}
}
return super.equals(obj);
}
@Override
public int hashCode() {
int result;
result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
return result;
}
}
为什么使用31 ,hashCode源码
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
本文地址:https://blog.csdn.net/WangKun_0612/article/details/107672060
上一篇: SpringBoot中使用策略模式
下一篇: rabbitmq的ttl和死信交换机
推荐阅读
-
java中hashCode和equals什么关系,hashCode到底怎么用的
-
java中为什么接口中的属性和方法都默认为public?
-
浅谈Java异常的Exception e中的egetMessage()和toString()方法的区别
-
浅谈Java中hashCode的正确求值方法
-
详解java中的深拷贝和浅拷贝(clone()方法的重写、使用序列化实现真正的深拷贝)
-
Java连载57-equals重写、finalize方法、hashCode方法
-
Java中 equals 和 == 的比较
-
java中List对象的操作方法和List对象的遍历
-
Java中成员变量与局部变量的区别、对象类型作为方法的参数和方法的返回值
-
荐 浅谈Java中类和对象的初始化、实例化以及方法重载的底层机制