[英]Unique Objects into list in java
我想根据对象的属性将唯一的对象添加到列表中。
class Employee {
protected long employeeId;
protected String firstName;
protected String lastName;
Employee(long employeeId,String firstName,String lastName){
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
}
}
我想基于唯一的'employeeId'
和'firstName'
将对象插入列表,将对象插入列表时组合应该是唯一的。
如果要使某些容器能够阻止添加Employee的重复项,则需要定义Employee中的均等计算方式。
public class Employee {
//...
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return new EqualsBuilder()
// if deriving: .appendSuper(super.equals(obj))
.append(employeeId, rhs.employeeId)
.append(firstName, rhs.firstName)
.append(lastName, rhs.lastName)
.isEquals();
}
}
如果希望某些容器能够快速查找Employee,则需要定义如何在Employee中计算哈希码。
public class Employee {
//...
@Override
public int hashCode() {
int hash = 1;
hash = hash * 17 + employeeId;
hash = hash * 31 + firstName.hashCode();
hash = hash * 13 + lastName.hashCode();
return hash;
}
}
大多数现代IDE都会为您提供重构功能。 在两个字段中使用相同的字段,以便它们一起更改。
因为您不希望重复,所以最好不要使用ArrayList,而是要注意哈希值并为您强制唯一性。 每当我在Java中选择一个容器时,我都会查看以下内容:
为了使所有这些可用,您不仅需要实现哈希码和等于 ,还需要实现比较器 。
只是要清楚一点,哈希的重点是提供查找速度。 等于的要点是定义哪些对象被视为相同。 比较器的重点是为对象提供排序。
如果要包括使用频率较低的容器,请尝试以下操作:
这可以通过覆盖equals()和hashCode()方法来实现-然后可以转到比较对象时使用这些方法的现有java.util集合类(例如HashSet)。
在这里,equals()和hashCode()方法被覆盖以满足给定的要求。
class Employee {
protected long employeeId;
protected String firstName;
protected String lastName;
Employee(long employeeId,String firstName,String lastName){
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
}
public boolean equals(Object o){
if(o == null) return false;
if(!(o instanceof) Employee) return false;
Employee other = (Employee) o;
if(this.employeeId != other.employeeId) return false;
if(! this.firstName.equals(other.firstName)) return false;
return true;
}
public int hashCode(){
return (int) employeeId * firstName.hashCode();
}
}
在这里,如果两个Employee对象相等,则它们还将具有相同的哈希码。 但是,即使两个Employee对象具有相同的哈希码也可能不相等。
例如:哈希码是将employeeId向下舍入为一个int。 这意味着许多雇员ID可能导致相同的哈希码,但是这些雇员对象仍然不相等,因为它们没有相同的雇员ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.