错误:无法将不兼容的类型对象转换为(java类)
我有java类适配器,这是一个错误(Groceries b:getData()),因为无法将对象转换为Groceries.java,如果我更改为(object b:getData()),则无法从Groceries.java调用方法b.getProduct().getSn() DataAdapter.java错误:无法将不兼容的类型对象转换为(java类),java,android,Java,Android,我有java类适配器,这是一个错误(Groceries b:getData()),因为无法将对象转换为Groceries.java,如果我更改为(object b:getData()),则无法从Groceries.java调用方法b.getProduct().getSn() DataAdapter.java public Groceries getBelBySN(String sn) { Groceries pp = null; for (Groceries b : getDat
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;
}
似乎
getData()
不返回Groceries对象。你能提供它的实现吗。
Java中的每个对象都继承自object.class,这就是为什么您可以毫无问题地对其进行强制转换。Object.class没有任何Groceries函数,这就是调用它们时出错的原因。您可能应该先读一本关于面向对象编程和Java中的面向对象编程的好书
编辑:
我不知道您的getData()
函数是什么样子的,但要使高级for循环工作,它应该是这样的:
ArrayList<Groceries> myGroceries = new ArrayList<Groceries>();
public ArrayList<Groceries> getData(){
return myGroceries;
}
getData()
返回什么?您能给我们看一下getData()
的代码吗?getData()来自列表
for (Groceries b : getData()) {
// Do stuff
}