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

后端 未结 4 1860
温柔的废话
温柔的废话 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:29

    I believe, the reason you are facing this issue is more due not following the code conventions, that any other.

    Whenever you make a collection of any objects, the convention is to use plurals for reference names of the collection. And singular reference name of the Object itself. You can find more details here.

    Below is the re-written code with the code conventions being followed:

    Method to create a list of objects of class Product:

    public List initProducts(){
        List products = new ArrayList();
        Product product = new Product(products.getId(), products.getItemName(), products.getPrice(), products.getCount());
        products.add(prod);    
    }
    

    Product Class:

    class Product {
    
    int itemCode;
    String itemName;
    double unitPrice;
    int count;
    
    public Product(int itemCode, String itemName, double unitPrice, int count)
    {
        this.itemCode = itemCode;
        this.itemName = itemName;
        this.unitPrice = unitPrice;
        this.count = count;
    }
    
    public int getId()
    {
       return this.itemCode;
    }
    
    public String getItemName()
    {
       return this.itemName;
    }
    
    public double getPrice()
    {
       return this.unitPrice;
    }
    
    public int getCount()
    {
       return this.count;
    }
    }
    

    Now, it is easy to see, that the products Object (which is of the type List) will not have any methods name getId() or getCount(). Infact , these are methods of the Object contained in the List.

    Following conventions will help you avoid, such hassles in futures.

提交回复
热议问题