我正在为测试人员学习java,帮助我弄清楚如何解决问题。有一个 Product 类,它包含有关产品的信息:id、价格、名称。因此,所有的 getter 和 setter。有一个 ProductRepository 类,它实现了通过 id 搜索产品和保存产品的方法。任务如下:在将新产品添加到存储库的方法中,应检查它是否还没有一个产品,其 id 与要添加的产品的 id 匹配。如果已经有一个,那么应该抛出你的异常——AlreadyExistsException。是否可以通过 findById 方法以某种方式做到这一点?这是我的代码:
public class ProductRepository {
private Product[] products = new Product[0];
public void save(Product product) {
//{
// throw new AlreadyExistsException(
// "Product with ID " + id + " already exist"
// );
//}
Product[] tmp = new Product[products.length + 1];
for (int i = 0; i < products.length; i++) {
tmp[i] = products[i];
}
tmp[tmp.length - 1] = product;
products = tmp;
}
public Product findById (int id) {
for (Product product : products) {
if (product.getId () == id) {
return product;
}
}
return null;
}
public Product[] getProducts() {
return products;
}
}
目前还不是很清楚问题是什么。在 save 方法的开头取并调用 findById 方法。