Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading