首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不会添加两个具有相同hashCode和equals (OK)的object,但contains()表示第二个对象不在集合中

不会添加两个具有相同hashCode和equals (OK)的object,但contains()表示第二个对象不在集合中
EN

Stack Overflow用户
提问于 2019-06-25 11:32:33
回答 1查看 32关注 0票数 0

我有一个测试,测试添加相同的边(Arista),但具有相同的顶点(但翻转顺序)是相同的(这不是一个有向图)。

这很奇怪,因为前两个断言通过了OK (添加Edge1Edge2将导致edges.sizes = 1,因为理论上它们是相同的)。

但是当测试edges.contains(Edge2)返回false时。

为什么它可以在测试添加时起作用(不重复添加),但在测试contains()时不起作用

代码如下:

代码语言:javascript
复制
    @Test
public final void testAristaWithSameVerticesIsNotAddedTwice() throws Exception {
    Grafo grafo = new Grafo();
    Vertice vertice1 = new Vertice("Vertice 1");
    Vertice vertice2 = new Vertice("Vertice 2");
    grafo.agregarVertice(vertice1);
    grafo.agregarVertice(vertice2);
    Arista arista = new Arista(vertice1, vertice2, 10);
    Arista arista2 = new Arista(vertice2, vertice1, 10);
    grafo.agregarArista(arista);
    grafo.agregarArista(arista);

    assertEquals(1, grafo.getAristasQuantity());
    assertTrue(grafo.hasArista(arista));
    assertTrue(grafo.hasArista(arista2)); // fails here
}

Grafo类:

代码语言:javascript
复制
private HashSet<Arista> aristas;

public boolean hasArista(Arista arista) {
    return this.aristas.contains(arista);
}

Arista类

代码语言:javascript
复制
package entities;

public class Arista {

    protected Vertice vertice1;
    protected Vertice vertice2;
    protected int peso;

    public Arista(Vertice vertice1, Vertice vertice2, int peso) {
        this.vertice1 = vertice1;
        this.vertice2 = vertice2;
        this.peso = peso;
    }

    public Vertice getVertice1() {
        return vertice1;
    }

    public Vertice getVertice2() {
        return vertice2;
    }

    public int getPeso() {
        return peso;
    }

    public void setPeso(int peso ) {
        this.peso = peso;
    }

    public int hashCode() {
        return vertice1.hashCode() + vertice2.hashCode();
    }

    public boolean equals(Arista arista) {
        if (arista == this) {
            return true;
        }
        if ((arista.getVertice1() == this.vertice1 && arista.getVertice2() == this.vertice2)
            || (arista.getVertice2() == this.vertice1 && arista.getVertice1() == this.vertice2)) {
            return true;
        }
        return false;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-06-25 11:49:11

我发现equals()没有覆盖父定义,因为它没有很好地定义。所以它不会被调用。

正确的方法是:

代码语言:javascript
复制
@Override
public boolean equals(Object object) {
    if (object instanceof Arista) {
        Arista arista = (Arista) object;
        if (arista == this) {
            return true;
        }
        if ((arista.getVertice1() == this.vertice1 && arista.getVertice2() == this.vertice2)
            || (arista.getVertice2() == this.vertice1 && arista.getVertice1() == this.vertice2)) {
            return true;
        }
    }
    return false;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56746462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档