gpt4 book ai didi

java - AssertEquals 与带有非原始模板参数的集合

转载 作者:行者123 更新时间:2023-12-01 15:40:34 28 4
gpt4 key购买 nike

我有一个字符串-数字对的类。该类实现了 compareTo 方法。

另一个类的方法返回pair类型的元素集合。

我想对此方法执行单元测试,因此编写了以下内容:

@Test
public void testWeight() {

Collection<StringNumber<BigDecimal>> expected = new Vector<StringNumber<BigDecimal>>();
expected.add(new StringNumber<BigDecimal>("a", BigDecimal.ONE));
expected.add(new StringNumber<BigDecimal>("b", BigDecimal.ONE));

Collection<StringNumber<BigDecimal>> actual = new Vector<StringNumber<BigDecimal>>();
expected.add(new StringNumber<BigDecimal>("a", BigDecimal.ONE));
expected.add(new StringNumber<BigDecimal>("b", BigDecimal.ONE));

//Collection<StringNumber<BigDecimal>> actual = A.f();

assertEquals(expected, actual);
}

但是正如您所看到的,即使集合中的元素相同,断言也会失败。可能是什么原因?

我得到的错误是

java.lang.AssertionError: expected: java.util.Vector<[a:1, b:1]> but was: java.util.Vector<[a:1, b:1]>

这对我来说并不有趣。

最佳答案

您的StringNumber类需要equals()方法。然后它就会起作用。假设此类包含 stringnumber 字段(由我的 IDE 自动生成):

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof StringNumber)) {
return false;
}
StringNumber that = (StringNumber) o;
if (number != null ? !number.equals(that.number) : that.number != null) {
return false;
}
return !(string != null ? !string.equals(that.string) : that.string != null);

}

@Override
public int hashCode() {
int result = string != null ? string.hashCode() : 0;
result = 31 * result + (number != null ? number.hashCode() : 0);
return result;
}

几点说明:

  • 两个 vector (为什么使用这种古老的数据结构)是相等的if :

both [...] have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).)

这就是为什么需要重写equals()

关于java - AssertEquals 与带有非原始模板参数的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8112938/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com