I have a StockList class which contains a linkedlist and can control stock using a variety of method. However i am stuck on what to put inside my method body for my updateItemPrice method.
Do I need to use a setter to set the new item price, if so how would i go about that?
This is my code so far, any help would be much appreciated!
import java.util.*;
public class StockList {
{
private LinkedList<StockItem> stock
= new LinkedList<StockItem>();
public StockList() {};
// Adds item to end of stock list
public void addItem(StockItem item)
{
this.stock.addLast(item);
}
// Removes item identified by productID from stock list
public void deleteItem(String itemID)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
stock.remove(itr.previousIndex());
break;
}
}
}
// Updates price of existing item
public void updateItemPrice(String itemID, double price)
{
???
}
// Updates quantity of existing item
public void updateItemQuantity(String itemID, int quantity)
{…}
// Updates re-order level of existing item
public void updateReOrderLevel(String itemID,
int reOrderLevel)
{…}
// Returns formatted representation of the stock list
public String formatStockList()
{…}
// Returns formatted representation of re-order list
// Items are on this list if quantity < reOrderLevel
public String formatReOrderList()
{…}
}
}
StockItem need to have the setter method to set Price like setPrice
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
item.setPrice(price);
break;
}
}
How ever there is also problem in your delete code...
public void deleteItem(String itemID)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
stock.remove(itr.previousIndex());
break;
}
}
}
This will give you concerrent Access exception. use below code instead.
public void deleteItem(String itemID)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
itr.remove(); // Removes last obejct returned by itr.next()
break;
}
}
}
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
item.setPrice(price);
break;
}
}
Nevertheless, it may be a better idea to use an HashMap<String, StockItem>() to store the ids of the stock objects and update the price would be more easy for you.
And you should store ids as Long instead of String, so this would be an HashMap<Long, StockItem>()
Since you have an itemId, I would not use a List. I would use a Map, with itemId as the key and the StockItem as the value. Then your add and delete methods become much simpler
Map<String, StockItem> stocks = new HashMap<String, StockItem>();
public void addStockItem(StockItem stockItem) {
this.stocks.put(stockItem.getItemId(), stockItem);
}
public void deleteStockItem(StockItem stockItem) {
this.stocks.remove(stockItem.getItemId());
}
then updating becomes as simple as getting the appropriate item out of the map and updating its price.
public void updateStockItem(String id, Double price) {
StockItem item = this.stocks.get(id);
item.setPrice(price);
}
// Updates price of existing item
public void updateItemPrice(String itemID, double price)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
item.setPrice(price);
break;
}
}
}
Everybody's answer here except #hvgotcodes has a very basic bug:
if(item.getitemID() == itemID) // this won't work!
#hvgotcodes solution is the correct way of implementing your class. Using a HashMap is far better than iterating over LinkedList to delete stuff.
Related
This is my assignment, I'm working on the step 3:
I need to implement a method called getItems() that takes a boolean value and returns a new ArrayList with items having the property that match the given value.
So far When I print it out it just shows the whole list in the array list, not only the objects having true property.
My code:
import java.util.ArrayList;
public class Shoppinglist9_6_pt2 {
ArrayList<Item> shoppingList = new ArrayList<>();
public Shoppinglist9_6_pt2(ArrayList<Item> shoppingList) {
this.shoppingList = shoppingList;
}
public void showList() {
for ( Item item : shoppingList){
System.out.printf("\nItem:%s Ct:%s", item.getName(),
item.getCt());
}
}
public ArrayList<Item> getItems(boolean gotIt) {
gotIt = true;
for (Item item : shoppingList){
if(item.getGotIt() == gotIt){
showList();
}else{
gotIt = false;
}
}
// Todo: return an ArrayList of item that
// match the gotIt true or false value.
// For example if set to True, then return
// an ArrayList of Item with gotIt=True.
return new ArrayList<Item>();
}}
public class Item {
private String name;
private int ct;
private boolean gotIt;
}
public Item(String name, int ct,boolean gotIt) {
this.name = name;
this.ct = ct;
this.gotIt = gotIt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCt() {
return ct;
}
public void setCt(int ct) {
this.ct = ct;
}
public boolean getGotIt(){
return gotIt;
}
public void setGotIt(boolean gotIt) {
this.gotIt = gotIt;
}
#Override
public String toString() {
return "Item :" +
"name='" + name + '\'' +
", ct=" + ct +
"Got it=" + gotIt;
}
}
This is my main:
public class inClass_Shopping_9_6_pt2 {
public static void main(String[] args) {
Shoppinglist9_6_pt2 sl = new Shoppinglist9_6_pt2();
sl.addItem( "Banana", 6,true);
sl.addItem("Coconut", 2,false);
sl.addItem("Apple", 12,true);
sl.getItems(true);
}
}
Also, you might observe the method gotIt() is grayed out & says parameters can be converted to a local varaible, same with the return. 'Item' in ArrayList<Items> is grayed out and says explicit type argument item can be replaced with <>, but this is the template my professor had sent us, and we need to follow it.
You have the new instance variable, you have the getters and setters, just the getItems method does not yet do the job...
You want to get a list with all the entries of the shopping list that have the attribute gotIt either true or false depending on the gotIt variable. How can you use the gotIt variable to get all the items you want?
Normally one would choose different names for the parameter of getItems, so it doesn't collide with the attributes name
You need to perform the following steps:
create a new ArrayList.
iterate through the sopping list and add each item with gotIt property matches the provided boolean value into the newly created ArrayList.
return the list.
That's how it might look like:
public ArrayList<Item> getItems(boolean gotIt) {
ArrayList<Item> items = new ArrayList<>();
for (Item item : shoppingList) {
if (item.getGotIt() == gotIt) {
items.add(item);
}
}
return items;
}
Note: although according to the assignment requirements you have to use ArrayList as a type in your code, it's not good practice to make the code dependent on concrete implementations. See What does it mean to "program to an interface"?
I know I have join party late, and my answer is not different from Alexandar.
I'm not offering a lot of assistance, still you can try using lambdas.
For instance
public ArrayList<Item> getItems(boolean gotIt) {
ArrayList<Item> items = new ArrayList<>();
shoppingList.forEach(item -> {
if(item.getGotIt() == gotIt) items.add(item);
});
return items;
}
For print,
sl.getItems(false).forEach(System.out::println);
Java noob here. I am trying to build a simple point of sale checkout application. I have a simple item database in mysql shown in the pic below.
I have an Item class built as below with getters and setters for each column
public class Item {
private String itemName;
private double unitPrice;
private boolean weightReqd;
private boolean quanReqd;
private boolean recalled;
private boolean ageRest;
private boolean eCpn;
private double eCpnAmt;
public Item(){}
public Item(String itemName, double unitPrice, boolean weightReqd, boolean quanReqd, boolean recalled,
boolean ageRest, boolean eCpn, double eCpnAmt){
this.itemName = itemName;
this.unitPrice = unitPrice;
this.weightReqd = weightReqd;
this.quanReqd = quanReqd;
this.recalled = recalled;
this.ageRest = ageRest;
this.eCpn = eCpn;
this.eCpnAmt = eCpnAmt;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public boolean isWeightReqd() {
return weightReqd;
}
public void setWeightReqd(boolean weightReqd) {
this.weightReqd = weightReqd;
}
public boolean isQuanReqd() {
return quanReqd;
}
public void setQuanReqd(boolean quanReqd) {
this.quanReqd = quanReqd;
}
public boolean isRecalled() {
return recalled;
}
public void setRecalled(boolean recalled) {
this.recalled = recalled;
}
public boolean isAgeRest() {
return ageRest;
}
public void setAgeRest(boolean ageRest) {
this.ageRest = ageRest;
}
public boolean iseCpn() {
return eCpn;
}
public void seteCpn(boolean eCpn) {
this.eCpn = eCpn;
}
public double geteCpnAmt() {
return eCpnAmt;
}
public void seteCpnAmt(double eCpnAmt) {
this.eCpnAmt = eCpnAmt;
}
}
And then i am using setters from the Item class to add the records to a List of Items (List).
public class CreateItemList {
private static Connection conn = null;
public List<Item> itemList = new ArrayList<Item>();
public void createDbConnection() throws ClassNotFoundException, SQLException {
String myUrl = "jdbc:mysql://localhost:3306/itemdb?autoReconnect=true&useSSL=false";
conn = DriverManager.getConnection(myUrl, "******", "*********");
}
public void addItemsToList() throws SQLException, ClassNotFoundException {
String query = "SELECT * FROM item_source";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
try
{
while (rs.next())
{
Item item = new Item();
item.setItemName(rs.getString("Item Name"));
item.setUnitPrice(rs.getDouble("Unit Price"));
item.setWeightReqd(rs.getBoolean("Weight Reqd"));
item.setQuanReqd(rs.getBoolean("Quan Reqd"));
item.setRecalled(rs.getBoolean("Recall"));
item.setAgeRest(rs.getBoolean("Age Rest"));
item.seteCpn(rs.getBoolean("Ecpn"));
item.seteCpnAmt(rs.getDouble("Ecpn Amt"));
itemList.add(item);
}
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e);
}
st.close();
}
}
Now the next thing i want to do is create exception handler methods. So if the user enters an item that is flagged as "true" for weight required, i want the is WeightReqd method to return true. But I'm struggling on this. I'm not sure how to return the boolean value for the item scanned, specifically for the Weight Reqd field.
public class ExceptionsHandler {
public boolean isWeightReqd(List<Item> itemList){
//HOW DO I RETURN THE BOOLEAN VALUE FOR THE WEIGHT REQD FIELD FROM THE LIST??
return false;
}
Would really appreciate the help! Can also take instructions on the general structure of this program, if there are better ways to do it!
You need to call your ExceptionHandler class for a specific item scanned. You dont need to pass the whole list in your isWeightReqd() method. Only pass your Item. Change your method signature to: public boolean isWeightReqd(Item itemList) and should get it.
I think this is a case where a hashmap might make more sense than an arraylist, using the name of the item as a key. Regardless once you have found that item all you need to call is
boolean b = item.isWeightReqd();
As per my understanding from your inputs in the comments, the user will enter the Item Name of an item and you want to return whether weight is required or not. So, the method signature would have the list of items from the DB and the item name entered by the user.
Option 1:
You can stream the contents of the list, find the item whose itemName matches the one entered by the user and return its weightReqd.
public boolean isWeightReqd(List<Item> itemList, String itemScanned) {
return itemList.stream()
.filter(item -> item.getItemName().equals(itemScanned))
.findFirst()
.map(Item::isWeightReqd)
.orElseThrow(() -> new RuntimeException("The item " + itemScanned
+ " does not exist"));
}
However, the worst-case running time for this is O(n) if the item scanned is not present or if it is the last one in the list.
Option 2:
If you want an O(1) lookup, you can convert the List<Item> after fetching it from the DB as a Map whose key is the itemName and value is the Item itself.
Map<String, Item> items = itemList.stream()
.collect(Collectors.toMap(Item::getItemName, Function.identity()));
public boolean isWeightReqd(List<Item> itemList, String itemScanned) {
if (items.containsKey(itemScanned)) {
return items.get(itemScanned).isWeightReqd();
}
throw new RuntimeException("The item " + itemScanned + " does not exist");
}
//Or by using Optional
Optional.ofNullable(items.get(itemScanned))
.map(Item::isWeightReqd)
.orElseThrow(() -> new RuntimeException("The item " + itemScanned
+ " does not exist"));
I'm using java 1.6.
I have a set of items, and each item has a name and a set of components. each component also has a name.
Set<Item>
Class Item
String name
Set<Component>
Class Component
String name
I'm now tasked with writing a method with input: item name + component name, and output: does this pair exist in the list of items.
public boolean hasItemComponentPair(String itemName, String componentName)
{
for(Item item : getItems())
{
if (item.getName() == itemName)
{
for(Component component : item.getComponents())
{
if (component.getName() == componentName)
{
return true;
}
}
}
}
return false;
}
The easiest way to do is by simply going through the elements of the sets one-by-one, and break if a match is found. This approach is doable for small sets.
My set of items is typically between 5 and 20 items, and the set of components is about the same. So there's between 25 and 400 unique item-component pairs. This amount of pairs seems too large for the naive algorithm to be efficient, especially if the method is called several times. But I also think a divide and conquer technique is too verbose for the given amount of elements.
What data structures and algorithms are typically used for this problem, keeping in mind the giving size of the sets?
If you can change your Item class you can do it like that:
class Item {
String name;
Map<String, Component> components;
}
In the map above key is the name of component.
Than change your code to:
public boolean hasItemComponentPair(String itemName, String componentName)
{
for(Item item : getItems())
{
if (item.getName().equals(itemName))
{
return item.getComponents().containsKey(componentName);
}
}
return false;
}
Now you need to traverse only one collection.
1) Sort the lists and do binary search on them.
2) Build indexes (typically as hashtable).
Override the equals and hashCode method in your Item and Component classes like following:
// Item.java
import java.util.Set;
public class Item
{
private String name;
private Set<Component> components;
public Item(String name)
{
this.name = name;
}
#Override
public int hashCode()
{
return name.hashCode();
}
#Override
public boolean equals(Object obj)
{
if (obj instanceof Item)
{
Item item = (Item) obj;
if (item.name != null && this.name != null)
return item.name.equals(this.name);
}
return false;
}
public Set<Component> getComponents()
{
return components;
}
public void setComponents(Set<Component> components)
{
this.components = components;
}
}
// Component.java
public class Component
{
private String name;
public Component(String name)
{
this.name = name;
}
#Override
public int hashCode()
{
return name.hashCode();
}
#Override
public boolean equals(Object obj)
{
if (obj instanceof Component)
{
Component component = (Component) obj;
if (component.name != null && name != null)
return component.name.equals(this.name);
}
return false;
}
}
This will give you constant time lookup. So you can search for elements in constant time.
Following is a demonstration:
import java.util.HashSet;
public class SearchDemo
{
public static void main(String[] args)
{
Item item1 = new Item("Item 1");
item1.setComponents(new HashSet<Component>());
item1.getComponents().add(new Component("Component A"));
item1.getComponents().add(new Component("Component B"));
item1.getComponents().add(new Component("Component C"));
Item item2 = new Item("Item 2");
item2.setComponents(new HashSet<Component>());
item2.getComponents().add(new Component("Component X"));
item2.getComponents().add(new Component("Component Y"));
item2.getComponents().add(new Component("Component Z"));
HashSet<Item> items = new HashSet<>();
items.add(item1);
items.add(item2);
// Input from user
String inputItem = "Item 2";
String inputComponent = "Component Y";
// Cast it to item and component
Item searchItem = new Item(inputItem);
Component searchComponent = new Component(inputComponent);
if (items.contains(searchItem)) // Constant time search
{
System.out.println("Contains Item");
for (Item item : items)
{
if (item.equals(searchItem))
{
if (item.getComponents().contains(searchComponent)) // Constant time search
{
System.out.println("Contains even the component");
}
}
}
}
}
}
The only issue is the for loop in the above lookup.
The item can be searched in constant time, but it has to be searched for again in the set (if it really exists) because I kind of fooled the program into believing that the searchItem is equal to the item in the set. Once the item is really found and its component set is extracted from it, its a constant time search for the componentItem.
If you have a HashMap of Components in the Item class, instead of the Set, and each key in the HashMap is the name of the component, then the input from the user can be searched in constant time!
This question already has answers here:
Java Printing Functions
(2 answers)
Closed 9 years ago.
I need help with these two functions print and printall which really do what the title of the functions says
// Prints a directory of all StockItems with their associated
// price, in sorted order (ordered by SKU).
public void printAll() {
}
// Prints a directory of all StockItems from the given vendor,
// in sorted order (ordered by SKU).
public void print(String vendor) {
}
Here is the full function below. DictionaryADT is a class that is used in implementing Hashtables and BST. The DictionaryADT just consists of functions. It has NOTHING to do with Map.
import data_structures.*;
import java.util.Iterator;
import java.util.Map;
public class ProductLookup {
DictionaryADT<String,StockItem> dictionary;
private int maxSize;
public ProductLookup(int maxSize, DictionaryADT<String,StockItem> dictionary) {
this(maxSize);
this.dictionary = dictionary;
}
// Constructor. There is no argument-less constructor, or default size
public ProductLookup(int maxSize) {
this.maxSize = maxSize;
}
// Adds a new StockItem to the dictionary
public void addItem(String SKU, StockItem item) {
dictionary.insert(SKU,item);
}
// Returns the StockItem associated with the given SKU, if it is
// in the ProductLookup, null if it is not.
public StockItem getItem(String SKU) {
if (SKU == null)
return null;
return dictionary.getValue(SKU);
}
// Returns the retail price associated with the given SKU value.
// -.01 if the item is not in the dictionary
public float getRetail(String SKU) {
if (!dictionary.contains(SKU))
return (float) -.01;
return getItem(SKU).getRetail();
}
public float getCost(String SKU) {
if (!dictionary.contains(SKU))
return (float) -.01;
return getItem(SKU).getCost();
}
// Returns the description of the item, null if not in the dictionary.
public String getDescription(String SKU) {
if (!dictionary.contains(SKU))
return null;
return getItem(SKU).getDescription();
}
// Deletes the StockItem associated with the SKU if it is
// in the ProductLookup. Returns true if it was found and
// deleted, otherwise false.
public boolean deleteItem(String SKU) {
if (SKU == null)
return false;
return dictionary.remove(SKU);
}
// Prints a directory of all StockItems with their associated
// price, in sorted order (ordered by SKU).
public void printAll() {
}
// Prints a directory of all StockItems from the given vendor,
// in sorted order (ordered by SKU).
public void print(String vendor) {
}
// An iterator of the SKU keys.
public Iterator<String> keys() {
return dictionary.keys();
}
// An iterator of the StockItem values.
public Iterator<StockItem> values() {
return dictionary.values();
}
}
Unfortunately it seems like java's Iterator cannot be sorted using built in functions as it is not a collection. You can, however, convert it to a List first, and then sort.
// Prints a directory of all StockItems with their associated
// price, in sorted order (ordered by SKU).
public void printAll() {
// Convert the iterator of SKU's to a List
List SKUList = new ArrayList();
Iterator<String> keyIt = dictionary.keys();
while( keyIt.hasNext() )
SKUList.add(it.next());
// Sort the SKU's
Collections.sort(SKUList);
// Print each item
for(int i=0; i<SKUList.size(); i++){
StockItem item = dictionary.getValue( SKUList.get(i) );
// Print what you want here
}
}
hey guys am not able iterate or get items from ItemSet following is my code
Item class
public class Item {
private String id;
private int count;
private String name;
public int getcount() {
return this.count;
}
public Item(String name) {
this.name=name;
this.id = "";
}
public Item(String id, String name) {
this.name=name;
this.id=id;
}
public Item(int count) {
this.count=count;
}
public String getItemName() {
return this.name;
}
public String getItemId() {
return this.id;
}
public Item returnItems(ItemSet itemset) {
Item item=null;
return item;
}
}
ItemSet Class holds List of items
public class ItemSet {
private List<Item> hold;
ItemSet(Item item) {
hold = new ArrayList<Item>();
this.hold.add(item);
}
ItemSet() {
//throw new UnsupportedOperationException("Not yet implemented");
}
public List<Item> getItemSet() {
return this.hold;
}
public void addItems(Item item) {
hold = new ArrayList<Item>();
this.hold.add(item);
}
}
This is my Transaction class holds list of ItemSets
public class Transaction {
private List<ItemSet> trans;
public ItemSet getUniqueItem() {
ResultSet rs;
Database d=new Database();
ItemSet unique=new ItemSet();
String query="Select id,name from item";
rs=d.sendQuery(query);
try{
while(rs.next()) {
System.out.println(rs.getString(1)+"\t"+rs.getString(2));
Item item=new Item(rs.getString(1),rs.getString(2));
unique.addItems(item);
}
} catch(Exception e) {
System.out.print(e.getMessage());
}
return unique;
}
}
And this is my main class
public class Ap {
public static void main(String args[]) {
Transaction t=new Transaction();
Transaction Ci=new Transaction();
Transaction Li=new Transaction();
ItemSet I=t.getUniqueItem(); //11
}
}
I dont know how to get Items from ItemSet at 11
I tried using
foreach(Item i:I) {
}
But I am getting error.
To be able to use for (Item i : itemSet), your ItemSet class must implement the iterable interface. You could do this by adding the following method to the ItemSet class:
public Iterator<Item> iterator() {
return hold.iterator();
}
Remember that you should add implements Iterable<Item> to the class declaration.
Note that you could always use for (Item i : itemSet.getItemSet()).
In order to use 'foreach' statement, your ItemSet class should implement java.lang.Iterable interface
UPDATE:
See this SO answer about how to implement Iterable interface
The getUniqueItem() method in your Transaction class returns an ItemSet which does not implement the Iterable interface, so you shouldn't expect to be able to iterate over it. You need to get the List<Item> from the ItemSet by calling getItemSet() and iterate over that.
By the way, getItemSet() is probably not a great name for that method, since it returns a List<Item>.
I think your code doesnt make alot of sense and i seriously dont understand why everybody wants to implement the Iterator interface.
First you make use the name Set for a class that contains a List.
Then you recreate a new instance of the List in the addItems() method, which should be addItem() because you want to add individual items to your list.
What you are doing is basically making a list and adding an item to it but the next item you add you recreate the list and you assign the reference of it to the reference of your previous list, thus effectively deleting it.
So you list will never contain more then 1 item.
If you want to have a list as an attribute of a class, then the name of the class you be intuitive, like ItemList for example because that tells you that you have a list of items and that is exactly what it is.
But if it contains only one list then actually its not needed at all because the only thing you do is add a method call in between. You can just use the List interface or any classes that implement it, like ArrayList for example.
I took your code and rewrote it like it would make sense.
I hope it helps you out ;)
public class Transaction {
public ItemList getUniqueItems() {
Database d = new Database();
ItemList unique = new ItemList();
String query="Select id,name from item";
ResultSet rs = d.sendQuery(query);
try {
while(rs.next()) {
System.out.println(rs.getString(1)+"\t"+rs.getString(2));
unique.addItem(new Item(rs.getString(1),rs.getString(2)));
}
}
catch(Exception e){
System.out.print(e.getMessage());
}
return unique;
}
}
public class Ap {
public static void main(String args[]) {
Transaction t = new Transaction();
ItemList i = t.getUniqueItems();
List<Item> list = i.getItemList();
list.get(10); //11 because 0 counts also
}
}
The shorter version would be:
1: the Transation class
public class Transaction {
public List<Item> getUniqueItems() {
Database d = new Database();
List<Item> unique = new ArrayList<Item>();
String query="Select id,name from item";
ResultSet rs = d.sendQuery(query);
try {
while(rs.next()) {
System.out.println(rs.getString(1)+"\t"+rs.getString(2));
unique.add(new Item(rs.getString(1),rs.getString(2)));
}
}
catch(Exception e){
System.out.print(e.getMessage());
}
return unique;
}
}
2: The Ap class:
public class Ap {
public static void main(String args[]) {
Transaction t = new Transaction();
List<Item> list = t.getUniqueItems();
list.get(10); //11 because 0 counts also
// iteration with a foreach loop
for (Item i : list) {
System.out.println(i);
}
// iteration with a for loop
for (int n = 0, s = list.size(); n < s; n++) {
System.out.println(list.get(n));
}
// iteration with a Iterator
Iterator<Item> iterator = list.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
So there is totally no need to implement the Iterator interface anywhere.