Java哈希集不';t添加两个hashCode相同且等于(OK)但contains()的对象表示第二个对象不在集合中
我有一个测试,测试添加相同的边(Arista)但具有相同的顶点(但翻转顺序)是相同的(这不是一个有向图) 这很奇怪,因为前两个断言通过了OK(添加Java哈希集不';t添加两个hashCode相同且等于(OK)但contains()的对象表示第二个对象不在集合中,java,equals,hashset,hashcode,Java,Equals,Hashset,Hashcode,我有一个测试,测试添加相同的边(Arista)但具有相同的顶点(但翻转顺序)是相同的(这不是一个有向图) 这很奇怪,因为前两个断言通过了OK(添加Edge1和Edge2将导致edges.size=1,因为理论上它们是相同的) 但是当测试edges.contains(Edge2)时,返回false 为什么在测试添加时它可以工作(不添加重复的添加),但在测试contains()时它不工作 代码如下: @Test public final void testAristaWithSameVert
Edge1
和Edge2
将导致edges.size=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);
}
我发现
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;
}
@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;
}