gpt4 book ai didi

java - for 循环内的 .contains()

转载 作者:行者123 更新时间:2023-12-01 15:29:08 26 4
gpt4 key购买 nike

我使用 for 循环在验证时迭代持久表单对象,然后与非持久表单对象进行比较。我在循环中使用 .contains,但是第一个循环返回 true,而每个其他循环返回 false,即使 pr 对象不包含 prPersist 对象。有人可以告诉我我做错了什么,或者是否有更好的方法来处理这个问题?谢谢

hibernate 实体

PurchaseRequest 对象

    @OneToMany(mappedBy = "purchaseRequest", cascade=CascadeType.ALL, orphanRemoval=true)

public List<LineItem> getLineItems() {
if(lineItems == null ){
lineItems = new ArrayList<LineItem>();
}
return lineItems;
}

public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}

LineItem 对象

@ManyToOne
@JoinColumn(name = "pr_id", nullable = false)
private PurchaseRequest purchaseRequest;

public PurchaseRequest getPurchaseRequest() {
return purchaseRequest;
}

public void setPurchaseRequest(PurchaseRequest purchaseRequest) {
this.purchaseRequest = purchaseRequest;
}

页面类

    private List<LineItem> lineItems;

private PurchaseRequest pr;

@Persist
private PurchaseRequest prPersist;

System.out.println("prPersist size " + prPersist != null ? prPersist.getLineItems().size() : "");
System.out.println("pr size outer loop " + pr.getLineItems().size());
if(prPersist != null) {
for(LineItem _lineItem : prPersist.getLineItems()) {
System.out.println("pr lineItem object value " + _lineItem.getQuantity());
System.out.println("pr lineItem size inner loop " + pr.getLineItems().size());
System.out.println("pr lineItem contains prPersist lineItem " + pr.getLineItems().contains(_lineItem));
if(!pr.getLineItems().contains(_lineItem)) {
_lineItem.setPurchaseRequest(pr);
pr.getLineItems().add(_lineItem);
System.out.println("new line item added");
}
}
prPersist = null;
}

打印结果

prPersist size 2
pr size outer loop 0
pr lineItem object value 4
pr lineItem size inner loop 0
pr lineItem contains prPersist lineItem false
new line item added
pr lineItem object value 5
pr lineItem size inner loop 1
pr lineItem contains prPersist lineItem true

设置prPersist

void onValidate() {
prPersist = null;

if (form.getHasErrors()) {
prPersist = pr;
}
}

最佳答案

鉴于 prPersist 和 'pr' 是不同的实例,我猜测每个包含的 LineItem 可能是不同的实例?

如果是这样,我猜您在 LineItem 上实现 equals 方法时遇到了问题。

关于java - for 循环内的 .contains(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9772359/

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