Collection.contains产生错误的结果

时间:2018-05-09 21:59:19

标签: java android collections

我有一个有几个字段的对象 - 你可以看到hashcode和equals方法只是在帐户中使用了id:

public class SpotResponse{
String id;
// bla bla other fields
public SpotResponse() {
}

public SpotResponse(@NonNull String id) {
    this.id = id;
}
public String getId() {
    return id;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    SpotResponse that = (SpotResponse) o;

    return id == that.id;
}

@Override
public int hashCode() {
    return id.hashCode();
}
}

我有一个检查Collection<SpotResponse> newSpots

的方法

包含oldSpot

中的一些HashMap<String, SpotResponse> spots = new HashMap<>();

如果我这样做:

List<String> newKeys = new ArrayList<>();

    for (SpotResponse response : newSpots) {
        newKeys.add(response.getId());
    }

    for (SpotResponse oldSpot : spots.values()) {
        if (newKeys.contains(oldSpot.getId())) {
            continue;
        }
        /* blabla */
    }

newKeys.contains()正确返回true,但如果我做了

newSpots.contains(oldSpot)

它总是返回false。在这种情况下,Collection是一个ArrayList(如果有任何帮助的话)

2 个答案:

答案 0 :(得分:2)

您的错误出现在equals实施中,在此行:

return id == that.id;

当您使用String时,您将两个id(即that.id==)与id.equals(that.id)进行比较。

答案 1 :(得分:0)

使用包含基本体时必须小心。 从技术上讲,String是一个包装字符元组的对象类,但是当你比较它时,它不是比较文字对象的内存指针,而是比较内存指针的值。

包含在引擎盖下使用.equals,所以当在你的类中重写equals时,你不能默认回到==比较,因为它比较地址而不一定是值。

希望有所帮助。