闲来没事尝试重写下equals和hashcode方法,笨人菜鸟,有错的地方恳请大佬指点。
import java.util.Objects;
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public User(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public User() {
super();
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
/**
* 重写equals方法的几个原则:
* 自反性:对于任意的对象x,x.equals(x)返回true(自己一定等于自己)
* 对称性:对于任意的对象x和y,若x.equals(y)为true,则y.equals(x)亦为true
* 传递性:对于任意的对象x、y和z,若x.equals(y)为true且y.equals(z)也为true,则x.equals(z)亦为true
* 一致性:对于任意的对象x和y,x.equals(y)的第一次调用为true,那么x.equals(y)的第二次、第三次、第n次调用也均为true,前提条件是没有修改x也没有修改y
* 对于非空引用x,x.equals(null)永远返回为false
*/
@Override
public boolean equals(Object obj) {
//自反性
if(this == obj) return true;
if(obj == null) return false;
if(!(obj instanceof User)) return false;
User other = (User) obj;
return getAge() == other.getAge() && Objects.equals(getName(), other.getName());
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (name == null ? 0 : name.hashCode());
result = 31 * result + (age == null ? 0 : age.hashCode());
return result;
}
}
简单测试代码:
import entity.User;
public class Distinct {
public static void main(String[] args) {
List<User> list = new ArrayList<>();
list.add(new User("李四",20));
list.add(new User("张三",18));
list.add(new User("马六",26));
list.add(new User("王五",23));
list.add(new User("宋奇",29));
list.add(new User("王五",23));
list.stream().forEach(System.out::println);
System.out.println("去重,但是一定要重写hashcode()和equals()方法");
list.stream().distinct().forEach(System.out::println);
User user1 = new User("2",2);
User user2 = new User("2",2);
User user3 = new User("3",2);
Set<User> userSet = new HashSet<>();
userSet.add(user1);
userSet.add(user2);
userSet.add(user3);
System.out.println(user3.equals(user2));
System.out.println(user1.hashCode() == user2.hashCode());
System.out.println(userSet);
}
}
结果:
User [name=李四, age=20]
User [name=张三, age=18]
User [name=马六, age=26]
User [name=王五, age=23]
User [name=宋奇, age=29]
User [name=王五, age=23]
去重,但是一定要重写hashcode()和equals()方法
User [name=李四, age=20]
User [name=张三, age=18]
User [name=马六, age=26]
User [name=王五, age=23]
User [name=宋奇, age=29]
false
true
[User [name=3, age=2], User [name=2, age=2]]
学习期间记笔记使用,可以参考,有错误的地方劳烦指点,谢谢~