Error: the method getId() is undefined for the type List

后端 未结 4 1912
温柔的废话
温柔的废话 2021-01-24 08:51

I have a method to create a list of objects of class

public List initProducts(){
    List product = new ArrayList();         


        
4条回答
  •  无人共我
    2021-01-24 09:28

    Is my statement correct??

    Product prod = new Product(product.getId(),product.getItemName(), product.getPrice(),  
    product.getCount());
    product.add(prod);
    

    NO this is incorrect. product is not an instance of class Product,rather it is an instance of List. List does not have any method called getId.

    If you want to retrieve the elements from the list and use it to create another instance of you can do something like:

    Product exisProd = product.get(0);
    Product prod = new Product(exisProd .getId(),exisProd .getItemName(), exisProd .getPrice(),  
        exisProd .getCount());
    

    But make sure that you have elements in the list, otherwise u may run into exception. product.add(prod);

提交回复
热议问题