如何在for循环中调用class参数?

how to call class parameter inside the for loop?

问题:无法在for循环语句中调用class参数

实施:我需要调用此 class 以便我的其余 api 列表能够正常工作并显示所有数据。

问题:无法在for循环语句中调用class参数

实施:我需要调用此 class 以便我的其余 api 列表能够正常工作并显示所有数据。

//this is working and able to get all the data, which the output is in "cmd";

public void ool8(){

     Product pBuilder = Product.newBuilder().build();
    ProductList productList =   productServiceBlockingStub.findAllRepeated(pBuilder);
     List<Product> products2 = productList.getProductList();
    
 
        for (Iterator iterator = products2.iterator(); iterator.hasNext();) {
            Product product = (Product) iterator.next();
            
             ProductEntity productEntity2 = new ProductEntity(
                     product.getPurchaseItem(),
                     product.getProductname(),
                     product.getProductbrand(),
                     product.getProductprice(),
                     product.getProductdescription(),
                     product.getProductquantity(),
                     product.getProductexpirationdate()
                     );

             List<ProductEntity> list = new ArrayList<>();
                
             list.add(productEntity2);
             
             System.out.println(list);
            
        }

//this is Not working cannot call the "productEntity2" outside the for loop;
//I need return in  a method List<ProductEntity> for rest api implementation.

public List<ProductEntity> ool8(){
    
    List<ProductEntity> list = new ArrayList<>();
    
     Product pBuilder = Product.newBuilder().build();
    ProductList productList =   productServiceBlockingStub.findAllRepeated(pBuilder);
     List<Product> products2 = productList.getProductList();
    
 
        for (Iterator iterator = products2.iterator(); iterator.hasNext();) {
            Product product = (Product) iterator.next();
            
             ProductEntity productEntity2 = new ProductEntity(
                     product.getPurchaseItem(),
                     product.getProductname(),
                     product.getProductbrand(),
                     product.getProductprice(),
                     product.getProductdescription(),
                     product.getProductquantity(),
                     product.getProductexpirationdate()
                     );

        }
    
    
        //this is the issue calling "productEntity2" outside of for loop
         list.add(productEntity2);
         
         System.out.println(list);
         
         return list;

        
}

productEntity2 位于 for 循环的 scope 中,您在那里创建了它。因此,您不能在循环(其范围)之外调用 productEntity2 。在我看来,对于 iterator 中的每个产品,您想向 list 添加一个实体,因此正确的做法是将 list.add(productEntity2); 放入 for 循环(在结束,创建 productEntity2).