Recursive Enumeration in Java
Posted
by Harm De Weirdt
on Stack Overflow
See other posts from Stack Overflow
or by Harm De Weirdt
Published on 2010-05-30T08:33:32Z
Indexed on
2010/05/30
8:42 UTC
Read the original article
Hit count: 227
Hello everyone.
I still have a question about Enumerations. Here's a quick sketch of the situation. I have a class Backpack that has a Hashmap content with as keys a variable of type long, and as value an ArrayList with Items. I have to write an Enumeration that iterates over the content of a Backpack. But here's the catch: in a Backpack, there can also be another Backpack. And the Enumeration should also be able to iterate over the content of a backpack that is in the backpack. (I hope you can follow, I'm not really good at explaining..)
Here is the code I have:
public Enumeration<Object> getEnumeration() {
return new Enumeration<Object>() {
private int itemsDone = 0;
//I make a new array with all the values of the HashMap, so I can use
//them in nextElement()
Collection<Long> keysCollection = getContent().keySet();
Long [] keys = keysCollection.toArray(new Long[keysCollection.size()]);
public boolean hasMoreElements() {
if(itemsDone < getContent().size()) {
return true;
}else {
return false;
}
}
public Object nextElement() {
ArrayList<Item> temporaryList= getContent().get(keys[itemsDone]);
for(int i = 0; i < temporaryList.size(); i++) {
if(temporaryList.get(i) instanceof Backpack) {
return temporaryList.get(i).getEnumeration();
}else {
return getContent().get(keys[itemsDone++]);
}
}
}
};
Will this code work decently? It's just the "return temporaryList.get(i).getEnumeration();" I'm worried about. Will the users still be able to use just the hasMoreElemens() and nextElement() like he would normally do?
Any help is appreciated,
Harm De Weirdt
© Stack Overflow or respective owner