【发布时间】:2013-10-29 07:04:33
【问题描述】:
回想起来,这个问题的答案可能会很明显,但现在我发现自己相当坚持这一点。我先给出一些代码块,然后提出问题。
这是我的Stockmanager类的一部分,我省略了一些与这个问题无关的方法。
import java.util.ArrayList;
public class StockManager
{
private ArrayList stock;
public StockManager()
{
stock = new ArrayList();
}
public void addProduct(Product item)
{
stock.add(item);
}
public Product findProduct(int id)
{
int index = 0;
while (index < stock.size())
{
Product test = stock.get(index);
if (test.getID() == id)
{
return stock.get(index);
}
index++;
}
return null;
}
public void printProductDetails()
{
int index = 0;
while (index < stock.size())
{
System.out.println(stock.get(index).toString());
index++;
}
}
}
这是我的类 Product,同样省略了一些方法。
public class Product
{
private int id;
private String name;
private int quantity;
public Product(int id, String name)
{
this.id = id;
this.name = name;
quantity = 0;
}
public int getID()
{
return id;
}
public String getName()
{
return name;
}
public int getQuantity()
{
return quantity;
}
public String toString()
{
return id + ": " +
name +
" voorraad: " + quantity;
}
}
我的问题在于 findProduct() 方法中出现编译时错误。更具体地说,Product test = stock.get(index); 行用 incompatible types 消息指示。
StockManager 的构造函数创建一个名为 stock 的新 ArrayList。从方法addProduct() 可以看出,这个ArrayList 包含Product 类型的项目。 Product 类有许多变量,其中一个称为 id 并且是整数类型。该类还包含一个方法getID(),它返回一个id。
据我所知,从数组列表中获取项目的方法是get() 方法,() 之间的数字表示项目的位置。看到我的arraylist 包含Product 的实例,当我在arraylist 上使用get() 方法时,我希望得到Product 作为结果。所以我不明白为什么当我定义一个名为 test 的 Product 类型的变量并尝试将 arraylist 中的一个项目分配给它时它不起作用。据我所知,我在 printProductDetails() 方法中成功使用了相同的技术,我在数组列表中的对象上使用 Product 中的 toString() 方法。
我希望有人能够为我澄清我的错在哪里。如果有什么不同,我在 BlueJ 中做这些东西,这可能不是最好的工具,但它是我应该用于这个学校项目的工具。
【问题讨论】:
-
只需要投
return (Product)stock.get(index);
标签: java arraylist bluej incompatibletypeerror