我正在使用HashSet将唯一用户添加到hashset。这些用户经常从在线源更新,当从那里读取它时,每次都会获得一个新对象,以便所有用户再次添加。
我的用户类中有一个UserID变量,并希望使用它来将用户添加到HashSet并确保唯一性。
private HashSet<User> userHashSet = new HashSet<User>();
userHashSet.add(user);
//based on the users id it will either add or not
我想这样做而不会失去效率,最好只有一个HashSet
答案 0 :(得分:4)
您应该在equals
课程中实施hashCode
和User
方法。
举个例子:
@Override
public int hashCode() {
return getUserId().hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof User &&
getUserId().equals(((User) obj).getUserId());
}
答案 1 :(得分:1)
您需要在hashCode
课程中实施equals
和User
方法。只要您正确实施这两种方法,您就会在HashSet
中获得唯一条目。
有很多关于如何正确实现这些内容的文章(例如What issues should be considered when overriding equals and hashCode in Java?),但最简单的方法是让IDE自动生成这些方法,或者使用Apache Commons帮助程序。