Java 查找ArrayList方法以查找数组方法

Java 查找ArrayList方法以查找数组方法,java,arrays,arraylist,Java,Arrays,Arraylist,我创建了一个在ArrayList中查找值的方法。我还复制了这个方法,这样我就可以将它用于我的数组,但是某些东西,比如get和size,不起作用。我不确定该如何重组它 public Product findProduct(String givenProduct) throws IllegalProductCodeException { IllegalProductCodeException notFoundMessage = new

我创建了一个在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;
            }

        }
公共产品findProduct(字符串givenProduct)抛出IllegalProductCodeException{
IllegalProductCodeException notFoundMessage
=新的非法ProductCodeException(“未找到产品”);
int size=产品的范围。长度;
int i=0;
布尔productFound=false;
while(!productFound&&i
替代
.get(i)
的数组将是
[i]
,替代
.size()
的数组将是
.length
替代
.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();
for(迭代器iter=products.Iterator();iter.hasNext();){
Product=iter.next();
编辑:Java 5的增强for循环相当于

for (Iterator<Product> iter=products.iterator(); iter.hasNext(); ) {
  Product product = iter.next();
for(迭代器iter=products.Iterator();iter.hasNext();){
Product=iter.next();

你能把你的答案告诉我吗?它看起来很有效率,但不太明白it@user3667111:这是Java 5中引入的foreach循环结构,它将自动循环整个数组(或集合,或实现Iterable的任何其他对象)对于你来说。如果你以前从未使用过它,你会喜欢它的。更多信息请访问。如果循环中的某个迭代找到匹配的元素,它会返回它(从而立即中断循环)。如果它到达列表的末尾(意味着它没有找到匹配项),它会抛出异常。你能告诉我你的答案吗?它看起来很有效,但不太明白it@user3667111:这是Java 5中引入的foreach循环结构,它将自动循环整个数组(或集合,或实现Iterable的任何其他对象)对你来说。如果你以前从未使用过它,你会喜欢它的。更多信息请访问。如果循环中的某个迭代找到了匹配的元素,它会返回它(从而立即跳出循环)。如果它到达列表的末尾(意味着它没有找到匹配),它会抛出异常。