Java HashSet не добавляет два объекта с одинаковым hashCode и равно (OK), но содержит () говорит, что второй объект не установлен - PullRequest
0 голосов
/ 25 июня 2019

У меня есть тест для проверки того, что добавление того же Edge (Arista), но с теми же вершинами (но с перевернутым порядком) одинаково (это не ориентированный граф).

И это странно, потому что два первых утверждения проходят успешно (добавление Edge1 и Edge2 приведет к edges.sizes = 1, поскольку они теоретически совпадают).

Но тогда при тестировании edges.contains(Edge2) возвращает false.

Почему это могло сработать при тестировании дополнения (чтобы не добавить дубликат), но не работает при тестировании contains()?

Это код:

    @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:

private HashSet<Arista> aristas;

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

Ариста класс

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;
    }
}

1 Ответ

1 голос
/ 25 июня 2019

Я обнаружил, что equals() не переопределяет родительское определение, потому что оно не было четко определено.Так что это не было вызвано.

Правильный путь:

@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;
}
...