Wai  Cheung Wai Cheung - 5 months ago 30
Java Question

How to return an arraylist iterator? (Java)

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?

Answer

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??
}