如何在java Set中存储唯一对象以避免重复?

mccptt67  于 5个月前  发布在  Java
关注(0)|答案(4)|浏览(56)

如何在java Set中存储唯一对象以避免重复?
例如
考虑Employee对象(Employee Id,name,salary....)
需要添加到Set中的对象的雇员列表。我们需要限制Set中需要通过“雇员ID”标识的重复元素。
最好的办法是什么?

5n0oy7gb

5n0oy7gb1#

如果你正在使用java.util.Set的实现,只要你的equalshashCode方法被正确实现,它就不应该允许重复。不知道为什么你的问题上有hashmap和hashtable作为标签。也许你应该重新措辞你的问题,并添加给你问题的代码?
编辑:考虑您的编辑:
如果你使用Set,你的员工应该有以下方法:

@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;
        Employee other = (Employee) obj;
        if (id == null) {
          if (other.id != null)
            return false;
        } else if (!id.equals(other.id))
          return false;
        return true;
      }

字符串

qmb5sa22

qmb5sa222#

与@Dirk类似,您也可以使用org. apache. commons中的HashCodeBuilder和HashsBuilder。
它看起来像这样:

@Override
public int hashCode() {
    return new HashCodeBuilder()
            .append(id)
            .append(name)
            .append(salary)
            .toHashCode();
}

@Override
public boolean equals(Object obj) {
    if (obj instanceof Employee) {
        final Employee employee = (Employee) obj;

        return new EqualsBuilder()
                .append(id, employee.id)
                .append(name, employee.name)
                .append(salary, employee.salary)
                .isEquals();
    } else {
        return false;
    }
}

字符串

mrphzbgm

mrphzbgm3#

“要在Set中存储唯一的用户定义对象,您必须显式地删除hashCodeequals方法以学生详细信息为例”

@Override
public int hashCode(){
   return this.id;
}
@Override
public boolean equals(Object obj)
{
     return this.hashCode==((Student)obj).hashCode();
}

字符串

pieyvz9o

pieyvz9o4#

设置仅存储唯一对象
例如:

Set set = new HashSet();
 // Add elements to the set
 set.add("a");//true
 set.add("b");//true
 set.add("c");//true
 set.add("d");//true
 set.add("a");//false

字符串
add将返回false,当你试图存储已经在Set中的对象

相关问题