尝试迭代 ArrayList<Obj> 的 class 时出现编译问题

compilation problem while trying to iterate a class of ArrayList<Obj>

I have a class to generate an Arraylist it all seems to work but in main it produces a compilation problem which I guess does not recognize my variable name as an ArrayList

public class Order {
//Attributes
private ArrayList<DessertItem> order;

//Constructors 
Order(){
    order = new ArrayList<DessertItem>();
}   

//Methods
public ArrayList<DessertItem> getOrderList(){
    return order;
}//end of getOrderList

public void add(DessertItem aItem) {
    order.add(aItem);
}//end of add

public int itemCount() {
    return order.size();
}//end of itemCount
}//end of class


public class DessertShop {
public static void main(String[] args) {

    //create order
Order order = new Order();

//create obj and adding to the order
Candy c1 = new Candy("Candy Corn", 1.5, .25);
order.add(c1);

for (DessertItem item : order) {//here is where is marked the error
System.out.printf("%s.%n", item.getName());
}

您的代码难以阅读。我建议注意格式。

orderOrder,而不是 ArrayList。它有一个 ArrayList。这就是您要迭代的内容。

试试这个:

for (DessertItem item : order.getOrderList()) {
    System.out.printf("%s.%n", item.getName());
}

你的很多评​​论都很混乱。我会删除它们。

我更喜欢 List<DessertItem> 的静态类型来订购。如果需要,您可以更改 List 的实现。