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

Time:05-07

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());
}

CodePudding user response:

Your code is hard to read. I'd recommend paying attention to formatting.

order is an Order, not an ArrayList. It has an ArrayList. That's what you want to iterate over.

Try this:

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

A lot of your comments are clutter. I'd remove them.

I'd prefer a static type of List<DessertItem> for order. You can change the implementation for the List if you need to.

  • Related