错误:对于List 类型,方法getId()未定义

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

public List initProducts(){ List product = new ArrayList(); 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()未定义类型List ,同样适用于其他方法。 请帮我解决这个错误。

我的陈述是否正确?

 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

如果要从列表中检索元素并使用它来创建另一个实例,则可以执行以下操作:

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

但请确保列表中包含元素,否则您可能会遇到exception。 product.add(PROD);

productList的参考

 List product = new ArrayList(); 

没有那种方法

product是对List对象的引用。

List/ArrayList没有名为getId()

您已为Prodct类编写了getId()方法,因此可以使用ref to Product类对象调用此方法。

如果要获取任何产品对象表单列表,请使用ArrayList get(int index)方法。

例如。

 Product prod = product.get(0); String id= prod.getId(); 

我相信,你面临这个问题的原因更多的是不遵循代码约定,任何其他。

每当您创建任何对象的集合时,约定是使用复数作为集合的引用名称。 以及Object本身的单数引用名称。 你可以在这里找到更多细节。

下面是重写代码,遵循代码约定:

创建类Product对象列表的方法:

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

产品类别:

 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; } } 

现在,很容易看出,产品Object(属于List类型)将没有任何方法名称getId()或getCount()。 事实上,这些是List中包含的Object的方法。

以下约定将帮助您避免期货中的此类麻烦。