错误:方法getId()未定义类型List< Product> [英] Error: the method getId() is undefined for the type List<Product>

查看:648
本文介绍了错误:方法getId()未定义类型List< Product>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种创建类对象列表的方法

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

public List<Product> initProducts(){
    List<Product> product = new ArrayList<Product>();

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

    return product;
}

我的产品类别是:

public class Product {

int ItemCode;
String ItemName;
double UnitPrice;
int Count;

/**
 * Initialise the fields of the item.
 * @param Name The name of this member of product.
 * @param id The number of this member of product.
 * @param Price The price of this member of product.
 */

public Product(int id, String Name, double Price, int c)
{
    ItemCode=id;
    ItemName=Name;
    UnitPrice=Price;
    Count = c;
}

public int getId()
{
   return this.ItemCode;
}

public String getItemName()
{
   return this.ItemName;
}

public double getPrice()
{
   return this.UnitPrice;
}

public int getCount()
{
   return this.Count;
}



/**
 * Print details about this members of product class to the text terminal.
 */
public void print()
{
    System.out.println("ID: " + ItemCode);
    System.out.println("Name: " + ItemName);
    System.out.println("Staff Number: " +UnitPrice);
    System.out.println("Office: " + Count);

}
}

我收到的错误是方法 getId()未定义类型列表< Product> ,与其他方法类似。请帮我解决这个错误。

I am getting an error that the method getId() is undefined for the type List<Product>, Similarly for other methods. Please help me out with this error.

我的陈述是否正确?

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


推荐答案

我的陈述是否正确?

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

这是不正确的。 product不是类 Product 的实例,而是 List 的实例。 List没有任何名为 getId 的方法。

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());

但要确保列表中有元素,否则你可能会遇到异常。
product.add(prod);

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

这篇关于错误:方法getId()未定义类型List&lt; Product&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆