错误:不兼容的类型对象无法转换为(java类)

时间:2017-05-19 05:47:03

标签: java android

我有java类适配器,这是错误(Groceries b:getData()),因为对象无法转换为Groceries.java,如果我改为(对象b:getData())我无法调用来自Groceries.java的方法b.getProduct()。getSn()

DataAdapter.java

public Groceries getBelBySN(String sn) {
    Groceries pp = null;
    for (Groceries b : getData()) {
        if (b.getProduct().getSn().equals(sn)) {
            pp = b;
            break;
        }
    }
    return pp;
}

public void updateTotal() {
    long jumlah = 0;
    for (Groceries b : getData()) {
        jumlah = jumlah + (b.getProduct().getHarga() * b.getQuantity());
    }
    total = jumlah;
}

这是我在适配器上调用的Groceries.java

public class Groceries {
protected Product product;
protected int quantity;

public Groceries(Product product, int quantity) {
    this.product = product;
    this.quantity = quantity;
}

public void setProduct(Product product) {
    this.product = product;
}

public Product getProduct() {
    return product;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}

public int getQuantity() {
    return quantity;
}

1 个答案:

答案 0 :(得分:1)

似乎getData()没有返回Groceries对象。请问你能为它提供实施吗? Java中的每个对象都继承自Object.class,这就是为什么你可以毫无问题地转换它。 Object.class没有任何Groceries函数,这就是调用它们时出错的原因。你应该首先在Java中阅读一本关于OOP和OOP的好书。

修改

我不知道你的getData()函数是怎么样的,但它应该是这样的,以使高级for循环工作:

ArrayList<Groceries> myGroceries = new ArrayList<Groceries>();

public ArrayList<Groceries> getData(){
    return myGroceries;
}

然后你的循环应该运行得很好。

for (Groceries b : getData()) {
    // Do stuff
}