在我的代码中,我有一组PlacesInfo对象,即。,
Set<PlacesInfo> placeId;
在这个集合中我添加了placeId(String)。我需要避免向我的HashSet添加重复项。这是我的覆盖方法。但是,它仍然是在我的集合中添加重复的元素。那么,如何避免这种情况?
@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;
}
答案 0 :(得分:1)
试试这个
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((placeId == null) ? 0 : placeId.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;
PlacesInfo other = (PlacesInfo) obj;
if (placeId == null) {
if (other.placeId != null)
return false;
} else if (!placeId.equals(other.placeId))
return false;
return true;
}
答案 1 :(得分:1)
试试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;
}
}
龙文是Maven可以使用的。你不需要把它包含在最后一个罐子里。仅用于编译。
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.8</version>
<scope>provided</scope>
</dependency>
答案 2 :(得分:0)
Below code working fine.If you remove equals and hashcode then it will add two elements.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
class PlacesInfo {
int placeId;
public int getId() {
return placeId;
}
PlacesInfo(int placeId) {
this.placeId = placeId;
}
public void setId(int placeId) {
this.placeId = placeId;
}
@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;
}
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + Objects.hashCode(this.placeId);
return hash;
}
}
public class Test {
public static void main(String[] args) {
PlacesInfo t1 = new PlacesInfo(1);
PlacesInfo t2 = new PlacesInfo(1);
System.out.println(t1.equals(t2));
Set<PlacesInfo> tempList = new HashSet<PlacesInfo>(2);
tempList.add(t1);
tempList.add(t2);
System.out.println(tempList);
}
}