Java 具有相同元素但不同值的哈希代码

Java 具有相同元素但不同值的哈希代码,java,hashcode,assertion,Java,Hashcode,Assertion,这是我的Heap 12文件,我的hashCode()不断出错。。。 请帮助,我得到了一个断言错误时,它应该是平等的 它看起来和我同龄人的密码很相似,导师也无法理解。 您的remove方法似乎没有达到预期效果。特别是: listArr[0] = listArr[size-1]; 更改元素的顺序,从而更改哈希代码 换句话说,添加然后删除元素不会使堆保持不变 您可以迭代两个堆的元素并打印它们以验证差异 编辑 我稍微修改了您的测试,以打印阵列的内容(我已为此公开): 因此,添加和删除在列表中留下了一个

这是我的Heap 12文件,我的hashCode()不断出错。。。 请帮助,我得到了一个断言错误时,它应该是平等的 它看起来和我同龄人的密码很相似,导师也无法理解。
您的
remove
方法似乎没有达到预期效果。特别是:

listArr[0] = listArr[size-1];
更改元素的顺序,从而更改哈希代码

换句话说,添加然后删除元素不会使堆保持不变

您可以迭代两个堆的元素并打印它们以验证差异

编辑

我稍微修改了您的测试,以打印阵列的内容(我已为此公开):


因此,添加和删除在列表中留下了一个额外的元素。

只是为了澄清。。。什么修复了删除方法?我不清楚怎样才能解决这个问题。问题不在于trickledown方法吗?

请发布您的异常堆栈跟踪。@DuncanJones我认为没有异常,只是测试失败。更改元素顺序是什么意思?这一行将最后一个元素放在堆的第一位。现在我知道您调用了
trickledown
,这改变了很多事情,但是测试失败的唯一原因是
heap.add(1000);heap.remove()在您希望堆是“中性”操作时更改堆。那么deos表示我的测试不好吗?@TimothyTurokDimChoi请参阅我的编辑-问题不在于测试,而是您的删除方法。
import java.util.*;
import junit.framework.*;            //Used for JUnit

public class Heap12Tester extends TestCase
{

public static void main(String args[])
{
  junit.swingui.TestRunner.main(new String[] {"Heap12Tester"}); 
 }

 public void testhashCode()
 {
 Heap12<Integer> sampleHeap = new Heap12<Integer>(); //instantiate two
 sampleHeap.add(100); //add two vales
 sampleHeap.add(0);
 Heap12<Integer> sampleHeap2 = new Heap12<Integer>(sampleHeap);
 assertEquals(sampleHeap.hashCode(), sampleHeap2.hashCode());
 sampleHeap.add(1000); //make the heaps uneven
 assertFalse(sampleHeap.hashCode() == sampleHeap2.hashCode());
 sampleHeap.remove(); //remove the values added

 assertTrue(sampleHeap2.equals(sampleHeap)); // <--------------------- error here
 assertTrue(sampleHeap.hashCode() == sampleHeap2.hashCode()); <--------- andhere
  }
  }
listArr[0] = listArr[size-1];
public void testhashCode() {
    Heap12<Integer> sampleHeap = new Heap12<Integer>(); //instantiate two
    sampleHeap.add(100); //add two vales
    sampleHeap.add(0);
    Heap12<Integer> sampleHeap2 = new Heap12<Integer>(sampleHeap);
    assertEquals(sampleHeap.hashCode(), sampleHeap2.hashCode());
    System.out.println(Arrays.toString(sampleHeap.listArr));
    sampleHeap.add(1000); //make the heaps uneven
    System.out.println(Arrays.toString(sampleHeap.listArr));
    assertFalse(sampleHeap.hashCode() == sampleHeap2.hashCode());
    sampleHeap.remove(); //remove the values added
    System.out.println(Arrays.toString(sampleHeap.listArr));

    assertTrue(sampleHeap2.equals(sampleHeap));
    assertTrue(sampleHeap.hashCode() == sampleHeap2.hashCode());
}
[100, 0, null, null, null]
[1000, 0, 100, null, null]
[100, 0, 100, null, null]