我制作了一个方法,在ArrayList中查找一个值。我还复制了这个方法,这样我就可以将它用于我的数组,但某些东西(如get和size)不起作用。我不确定该如何重组。
public Product findProduct(String givenProduct) throws IllegalProductCodeException {
IllegalProductCodeException notFoundMessage
= new IllegalProductCodeException("Product was not found");
int size = rangeOfProducts.length;
int i = 0;
boolean productFound = false;
while (!productFound && i < size) { //While book hasn't been found and i is less than the size of the array
productFound = rangeOfProducts.get(i).getProductCode().equals(givenProduct);
//Checks whether the given value in the array's reference is equal to the given reference entered
i++; //if not then add 1
}
if (productFound) {
return rangeOfProducts.get(i - 1);
} else {
throw notFoundMessage;
}
}
.get(i)
的替代数组将为[i]
,.size()
的替代数组为.length
。
for (Product product : products) {
if (product.getProductCode().equals(givenProduct)) {
return product;
}
}
throw new IllegalProductCodeException("Product was not found");
编辑:Java 5增强的for循环相当于
for (Iterator<Product> iter=products.iterator(); iter.hasNext(); ) {
Product product = iter.next();