2017-05-19 51 views
-2

我有java类适配器,这是错误的(Groceries b:getData()),因为对象无法转换为Groceries.java,如果我改为(Object b:的getData())我不能从Groceries.java调用一个方法b.getProduct()getSn()错误:不兼容的类型对象不能转换为(java类)

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

getData()返回什么?你能告诉我们'getData()'的代码吗? –

+0

getData()是从列表 – Rizal

回答

0

看起来好像getData()不会返回一个Groceries对象。你能提供它的实施吗? Java中的每个对象都从Object.class继承,这就是为什么您可以毫无问题地投射到它的原因。 Object.class没有任何你的Groceries函数,这就是为什么你调用它们时出错。您应该首先阅读一本关于Java中的OOP和OOP的好书。

编辑:

我不知道你的getData()功能的模样,但它应该是这样的,使先进的循环工作:

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

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

那么你的循环应该运行得很好。

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

谢谢你现在工作,我添加到适配器 – Rizal

相关问题