package com.ddy; public class User { private Integer id; private String name; private String address; private String phone; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } public User(Integer id) { super(); this.id = id; } }
Person根据id重写了equals和hashCode方法;这样HashSet添加people的时候会将id重复的people对象视为同一个people对象。
package com.ddy;
import java.util.HashSet;
import java.util.Set; public class Test {
public static void main(String[] args) {
User user1 = new User(1);
User user2 = new User(1);
Set<User> users = new HashSet<>();
users.add(user2);
users.add(user1);
System.out.println(users);
}
}
输出结果:[com.ddy.User@20]