Java arraylist不兼容类型错误

Rai*_*ier 1 java arraylist incompatibletypeerror bluej

回想起来,答案可能会显而易见,但现在我发现自己相当坚持这一点.我先给出一些代码块然后再提出问题.

这是我的类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++;
    }
}
Run Code Online (Sandbox Code Playgroud)

}

这是我的类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;
}
Run Code Online (Sandbox Code Playgroud)

}

我的问题在于我在findProduct()方法中遇到编译时错误.更具体地说,该行Product test = stock.get(index);用消息不兼容的类型表示.

StockManager的构造函数创建一个ArrayList名为stock 的new .从该方法可以看出,addProduct()ArrayList包含该类型的项目Product.的Product类有许多变量其中之一被称为ID和是整数类型.该类还包含一个getID()返回id的方法.

据我所知,从arraylist获取项目的get()方法是在()之间用数字表示项目位置的方法.看到我的arraylist包含实例Product,Product当我get()在arraylist上使用该方法时,我希望得到一个结果.所以我不明白为什么当我定义一个名为Test的变量类型的变量并尝试将一个项目从arraylist分配给它时它为什么不起作用.据我所知,我在方法printProductDetails()中成功地使用了相同的技术,我使用了toString()来自arraylist的对象的Product方法.

我希望有人能够为我澄清我的错.如果它有任何区别,我在BlueJ做这个东西,这可能不是最好的工具,但它是我应该用于这个学校项目的那个.

yam*_*tes 6

private ArrayList stock;
Run Code Online (Sandbox Code Playgroud)

您应该使用有界类型重新声明它,如下所示:

private List<Product> stock = new ArrayList<Product>();
Run Code Online (Sandbox Code Playgroud)

如果你不这样做,这一行:

Product test = stock.get(index);
Run Code Online (Sandbox Code Playgroud)

将无法正常工作,因为您正在尝试将原始分配Object给a Product.

其他人建议将其投射Object到a Product,但我不建议这样做.