gpt4 book ai didi

Java断言相同的值但出错

转载 作者:行者123 更新时间:2023-11-30 07:11:30 25 4
gpt4 key购买 nike

我正在使用两个列表并尝试使用 contains()。我没有违反约定,但我的类对 contains 的使用仍然是错误的。

项目.class

 class Items implements Comparable<Items> {
private String name;
private Date date;
private Lib.CLASSENUM type;

public getDate();
public setDate();

....
public compareTo(Items o) {
...
}
}

测试类

List<Items> actualList;
List<Items> expectedList;

public setup() {
actualList = new ArrayList<>();
expectedList = new ArrayList<>();
}

class Tests {
@Test
public void statusCheckValidatingRedLinePromotionItemsTest() {
//this just sets the two ArrayList to clear
clearProductMaps();
Items goodsItem = new Items();

goodsItem.setName("Product_A");
goodsItem.setPrice(4.10);
goodsItem.setStatus(Lib.CLASSENUM.ORIGINAL);
goodsItem.setDate(date);

actualList.add(goodsItem);
goodsItem = new Items();
goodsItem.settName("Product_A");
goodsItem.setPrice(3.70);
goodsItem.setStatus(Lib.CLASSENUM.PROMO);
date = calendar.getTime();
goodsItem.setDate(date);

actualList.add(goodsItem);
goodsItem = new Items();
goodsItem.setName("Product_A");
goodsItem.setPrice(3.70);
goodsItem.setDate(date);
goodsItem.setStatus(Lib.CLASSENUM.PROMO);
expectedList.add(goodsItem);

assertTrue(expectedGoods.get(0).contains(actualList.get(0));
}

包含内容应该是真实的,不是吗?(o==null ? e==null : o.equals(e))

最佳答案

您没有获得匹配的项目,因为 contains(..)方法ArrayList依赖于相等性检查,而不是 Compararble<T>实现。

一旦您覆盖并实现 equals(..)hashCode()Item类,测试即将通过。

或者,您可以使用 TreeSet<T> ,它依赖于Compararble<T> ,代替ArrayList<T>检查遏制。

关于Java断言相同的值但出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39170958/

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