[英]Removing specific element from ArrayList
我需要从arrayList删除刚刚添加的元素的帮助。
我有一个private static ArrayList<Position> positions = new ArrayList<>()
向其中添加Position
类的对象,这些对象的参数为name
, quantity
和price
。
比我有一种将对象添加到列表中的方法,如果第二次添加相同的产品,则应该将数量添加到该名称的第一个对象中,然后删除第二个。
到目前为止,我有这种方法:
public void addPosition(Position p) {
for (Position poz: positions) {
if (poz.getname().equals(p.getname())) {
poz.setquantity(poz.getquantity() + p.getquantity());
}
} positions.add(p);
}
添加数量可以很好地工作,但是在删除具有重复名称的元素时遇到了问题。
请帮忙。
您不应该添加重复的项目然后将其删除。 只需声明一个可以正确添加项目的方法即可; 也就是说,如果不存在,它将添加物料;如果存在,则将更新数量。
它看起来应该像这样:
public void addPosition(Position addition) {
//flag to track whether the new item exists in the list
boolean itemExists = false;
//go through the list looking for an item with the passed name to update
for (Position existing : positions) {
if (existing.getName().equals(addition.getName())) {
existing.setQuantity(existing.getQuantity() + addition.getQuantity());
itemExists = true;
}
}
//if no matching item was found, add the new item
if (!itemExists) {
positions.add(addition);
}
}
以上应该可以。 如果您关心性能,最好使用HashMap
以便您可以按名称查找Position
而不是每次都遍历整个列表。
如果您想了解其他数据结构,我想建议您使用HashSet ,默认情况下,它不会为原始对象插入重复项。 在您的情况下,您唯一需要对Position类进行的操作就是添加equals和hashCode方法。 例如,Eclipse会以自己的方式来创建和安装。
hashCode()
如您所知,此方法提供了对象的has代码。 基本上,Object提供的hashCode()的默认实现是通过将内存地址映射到整数值来派生的。 如果查看Object类的源代码,则将为hashCode找到以下代码。 public native int hashCode(); 它表明hashCode是本机实现,可以在一定程度上提供内存地址。 但是,可以在实现类中覆盖hashCode方法。
等于()
此特定方法用于在两个对象之间进行相等比较。 Java有两种类型的比较。 一种是使用“ = =”运算符,另一种是“ equals()”。 我希望您知道这两者之间的区别。 更具体地说,“。equals()”是指等价关系。 因此,从广义上讲,您说两个对象相等,它们满足“ equals()”条件。 如果查看Object类的源代码,您将找到equals()方法的以下代码。
这是一个完整的工作示例(您可以按照以下步骤修改您的课程)
import java.util.HashSet;
public class Zhashset{
private int num;
public Zhashset(){
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + num;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Zhashset other = (Zhashset) obj;
if (num != other.num)
return false;
return true;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Zhashset> hs = new HashSet<Zhashset>();
hs.add(new Zhashset());
hs.add(new Zhashset());
for(Zhashset item : hs)
System.out.println(item.getNum());
}
}
输出将是: 0只写一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.