1

I'm new in java programming. I have searched several posts that related to iterator but still cannot figure out how to do it.

I have 2 classes. Order and OrderItem. I need to implement the interface Iterable<OrderItem> to being able to iterate through the items using the for-each loop.

public class OrderItem {
    private Product product;
    private int quantity;

    public OrderItem(Product initialProduct, int initialQuantity)
    {
        this.product = initialProduct;
        this.quantity = initialQuantity;
    }
    public Product getProduct()
    {
        return this.product;
    }

    public int getQuantity()
    {
        return this.quantity;
    }

This is the class Order

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Order implements Iterable<OrderItem> {

private List<OrderItem> items = new ArrayList<OrderItem>();

    public Order()
    {
    }

    public void addItem(OrderItem orderitem)
    {
        items.add(orderitem);
    }

    public Iterator<OrderItem> iterator()
    {
        return this.iterator(); //How to do this part??
    }

    public int getNumberOfItems()
    {
        return items.size();
    }
    }

Here What does it mean to return an iterator? Java suggests doing it like what i learn about linked list. But i am using ArrayList now. I don't need to do like this? Or do I?

3
  • What's wrong with returning items.iterator()? Commented Jun 19, 2016 at 18:23
  • Stackoverflow error Commented Jun 19, 2016 at 18:33
  • Oops... I made a stupid mistake. It seems fine when i changed items.iterator(). Thank you for helping! Commented Jun 19, 2016 at 18:36

1 Answer 1

1

You can take the iterator from the List of OrdemItem here:

private List<OrderItem> items = new ArrayList<OrderItem>();

and do:

public Iterator<OrderItem> iterator()
{
    return items.iterator();  
}

instead of doing

public Iterator<OrderItem> iterator()
{
    return this.iterator(); //How to do this part??
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.