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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12776813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:10:31  来源:igfitidea点击:

How to Store unique objects to avoid the duplicates in java Set?

javahashmapsethashtable

提问by iamjustcoder

How to Store unique objects to avoid the duplicates in java Set?

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

For example

例如

Consider Employee object which (Employee Id, name, salary....)

考虑 Employee 对象(员工 ID、姓名、薪水....)

list of employee of objects need to add in the Set. We need to restrict the Set for the duplicate elements which need to identify by the "Employee Id.

对象的雇员列表需要添加到集合中。我们需要限制需要通过“员工 ID.

What are the best way's to do?

最好的方法是什么?

回答by Dirk

If you are using an implementation of a java.util.Set, it should not allow duplicates as long as your equalsand hashCodemethods are implemented properly. Not sure why you have hashmap and hashtable as tags on your question though. Maybe you should rephrase your question and add the code that gives you issues?

如果您正在使用 a 的实现java.util.Set,则只要您的equalshashCode方法正确实现,就不应该允许重复。不知道为什么你有 hashmap 和 hashtable 作为你的问题的标签。也许您应该重新表述您的问题并添加给您带来问题的代码?

Edit: considering your edit:

编辑:考虑您的编辑:

If you use a Set, your Employee should have the following methods:

如果您使用 a Set,您的 Employee 应该有以下方法:


    @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;
      }

回答by hipokito

Similarly to @Dirk, you can also use HashCodeBuilder and EqualsBuilder from org.apache.commons.

与@Dirk 类似,您也可以使用 org.apache.commons 中的 HashCodeBuilder 和 EqualsBuilder。

It would look like this:

它看起来像这样:

@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(id, employee.name)
                .append(id, employee.salary)
                .isEquals();
    } else {
        return false;
    }
}

回答by saum22

Set Stores unique object only

Set 仅存储唯一对象

Eg:

例如:

 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 will return false when you will try to store the object which is already in the Set

当您尝试存储已经在 Set 中的对象时,add 将返回 false