当检查实例与其他实例相等时,我得到
java.lang.StackOverflowError
.
因为存在双向关系,所以我的Override equal method
调用equal()
函数相互递归。我应该删除一侧override equal method
的一张支票相等条件吗?有什么更好的方法?一些 PG 建议我使用EqualsBuilder
Apache。
订单项.java
public class OrderItem {
private String id;
private Order order;
public OrderItem(String id, Order order) {
this.id = id;
this.order = order;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setOrder(Order order) {
this.order = order;
}
public Order getOrder() {
return order;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof OrderItem)) {
return false;
}
final OrderItem other = (OrderItem)object;
if (!(id == null ? other.id == null : id.equals(other.id))) {
return false;
}
if (!(order == null ? other.order == null : order.equals(other.order))) {
return false;
}
return true;
}
}
订单.java
public class Order {
private String id;
private List<OrderItem> orderItemList;
public Order(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setOrderItemList(List<OrderItem> orderItemList) {
this.orderItemList = orderItemList;
}
public List<OrderItem> getOrderItemList() {
return orderItemList;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof Order)) {
return false;
}
final Order other = (Order)object;
if (!(id == null ? other.id == null : id.equals(other.id))) {
return false;
}
if (!(orderItemList == null ? other.orderItemList == null : orderItemList.equals(other.orderItemList))) {
return false;
}
return true;
}
}
测试
public static void main(String[] args) {
Order order1 = new Order("1");
List<OrderItem> orderItemList = new ArrayList<OrderItem>();
orderItemList.add(new OrderItem("1", order1));
orderItemList.add(new OrderItem("2", order1));
order1.setOrderItemList(orderItemList);
Order order2 = new Order("1");
List<OrderItem> orderItemList2 = new ArrayList<OrderItem>();
orderItemList2.add(new OrderItem("1", order2));
orderItemList2.add(new OrderItem("2", order2));
order2.setOrderItemList(orderItemList2);
if(order1.equals(order2)) {
System.out.println("Equal");
} else {
System.out.println("Not Equal");
}
}