如何存储独特的对象以避免java Set中的重复? [英] How to Store unique objects to avoid the duplicates in java Set?

查看:330
本文介绍了如何存储独特的对象以避免java Set中的重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如

考虑Employee对象(Employee Id,name,salary ....)

对象的雇员列表需要在Set中添加。
我们需要限制Set对于需要通过员工ID识别的重复元素。



最好的方法是什么?

解决方案

如果您正在使用 java.util.Set 的实现,只要你的等于 hashCode 方法正确实现,就不应该允许重复。不知道为什么你有hashmap和hashtable作为标签在你的问题,虽然。也许你应该改写你的问题,并添加代码给你的问题?



编辑:考虑您的编辑:

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

  @Override 
public int hashCode(){
final int prime = 31;
int result = 1;
result = prime * result +((id == null)?0:id.hashCode());
返回结果;
}

@Override
public boolean equals(Object obj){
如果(this == obj)
返回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;
返回true;
}


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

For example

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

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.

What are the best way's to do?

解决方案

If you are using an implementation of a java.util.Set, it should not allow duplicates as long as your equals and hashCode methods 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?

Edit: considering your edit:

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

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

这篇关于如何存储独特的对象以避免java Set中的重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆