我是一個Java新手..但我相信我可以以高效的方式完成這項工作。添加到數組列表
此方法的目的是添加具有唯一標識的產品。如果我的產品重複,我應該拋出異常。那麼,這個序列不適用於多線程環境。
public void addProduct(Product product)
throws ProductAlreadyExistsException {
product.id = ++nextId;
this.id = product.id;
Iterator<Product> it = allProducts.iterator();
Product p= null;
boolean flag= false;
if (!allProducts.isEmpty()) {
while(it.hasNext()){
p= it.next();
if (p.getName() == product.getName())
throw new ProductAlreadyExistsException(p.getName());
else
flag = true;
}
}
else
allProducts.add(product.id-1, product);
if(flag){
allProducts.add(product.id-1, product);
}
}
我想要的是這樣的。
for (Product p : allProducts) {
if (p.getName() == product.getName()) {
throw new ProductAlreadyExistsException(p.getName());
}
allProducts.add(p);
}
}
這是行不通的。 感謝指導我..
在Product中實現equals()方法好得多,所以它們可以將自己與其他對象進行比較。在這樣做的時候,還要記得實現hashCode。 IDE可以爲你自動生成這兩種方法。關於equals和hashCode合約,請閱讀[this](http://www.coderanch.com/t/269905/java-programmer-SCJP/certification/hashcode-equals-contract)。 – LexLythius
我做了上述改變,它效果更好。非常感謝 – Newbie