在我的代码中,我有一组 PlacesInfo 对象,即
Set<PlacesInfo> placeId;
在这个集合中,我添加了 placeId(字符串)。我需要避免向我的哈希集中添加重复项。下面是我的覆盖方法。但是,它仍然向我的集合添加重复的元素。那么,如何避免这种情况呢?
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + Objects.hashCode(this.placeId);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return true;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final PlacesInfo other = (PlacesInfo) obj;
if (!Objects.equals(this.placeId, other.placeId)) {
return false;
}
return true;
}
最佳答案
尝试Lombok 。我已将 GAgarwal 解决方案简化为一个简单的类。
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@EqualsAndHashCode(of={"placeId"})
public class PlacesInfo{
@Getter; @Setter;
int placeId;
PlacesInfo(int placeId) {
this.placeId = placeId;
}
}
Lombok 由 Maven 提供。您不需要将其包含在最终的 jar 中。仅用于编译。
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.8</version>
<scope>provided</scope>
</dependency>
关于java - 如何重写hashcode和equals方法以避免在java中的HashSet中添加重复的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28802761/