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
上一篇: Java入门小项目01
推荐阅读
-
Java8利用stream的distinct()方法对list集合中的对象去重和抽取属性去重
-
Java中构造方法和代码块的执行顺序
-
Java中如何正确重写equals方法
-
浅谈java 重写equals方法的种种坑
-
Java 中的 equals,==与 hashCode 的区别与联系
-
java中hashCode和equals什么关系,hashCode到底怎么用的
-
java中为什么接口中的属性和方法都默认为public?
-
浅谈Java异常的Exception e中的egetMessage()和toString()方法的区别
-
浅谈Java中hashCode的正确求值方法
-
详解java中的深拷贝和浅拷贝(clone()方法的重写、使用序列化实现真正的深拷贝)