![](/img/trans.png)
[英]How do I find the index of multiple objects in an ArrayList when they are identitcal
[英]How do I find objects in an ArrayList superclass?
我有一个继承自超类Basket
的子类BetterBasket
,而超类Basket
本身又继承自ArrayList<Product>
。 我的方法add
在BetterBasket
增加了一个项目寻遍ArrayList
,如果有相同的类型,那么这些值必须添加到已经存在的对象的对象(合并quantity
和price
),如果没有对象必须加入到ArrayList
。 这是我的代码,但无法正常工作,因为它将根据需要添加产品,但不会合并相同的产品。 因此,它不使用代码的else部分。
@Override
public boolean add(Product pr)
{
if (!this.contains(pr)){ //if array doesn't contain the item
super.add(pr); //adds item
} else { //add item quantity and price to existing item.
double x = pr.getPrice();
int q = pr.getQuantity();
for (int i=0; i < super.size(); i++) //loop through array
{
if (super.get(i).equals(pr)){ //if item is same as item within
//the array
int w = super.get(i).getQuantity();
double y = super.get(i).getPrice();
super.get(i).setQuantity(q + w);
super.get(i).setPrice(y + x);
}
}
}
return true;
}
我应该在第一个if
语句中使用this
还是super
? 为什么不使用else
分支?
永远不会选择else
分支的原因是因为contains
总是返回false
。 造成这种情况的最可能原因是因为您的组件元素Product
不会覆盖equals
和hashCode
:
public boolean contains(Object o)
:如果此列表包含指定的元素,则返回true。 更正式地讲,当且仅当此列表包含至少一个元素(e == null?e == null:o.equals(e))时,返回true。 ArrayList.contains
另请参阅这篇文章 。
出于同样的原因,在for
循环中使用equals
也不太可能做您想要的事情。 根据您的要求,看起来HashMap
可能是数据结构的更好选择。
当我们讨论它时,考虑使用组合而不是继承来访问ArrayList
功能可能是一个好主意。 也建议不要使用浮点类型来表示货币。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.