I’m almost finished with my project, although there is one thing that I can’t get past.
Let me quote it first:
The class Board must also oer a method that returns an iterator that will
return all the elements on the board (not including items carried by robots) that
satisfy a given condition. Examples of conditions are all elements that have an
energy of at least 1000 Ws (the iterator will then not return walls nor surprise
boxes, because they have no known energy), all elements in some sub range of
the board, all items on the board, etc.
So, I have a board with elements on. (Robots, certain items, walls, …)
In class we have seen how to implement Iterable, and override the method iterator() if needed, but now I need to pass conditions as a parameters to this iterator?
My best shot was this method in class Board:
public Iterator<Element> getAllElementsByCondition(boolean condition) {
HashSet<Element> result = new HashSet<Element>();
for (Element element : elements)
if (Board.this.hasElement(element) && condition)
result.add(element);
return result.iterator();
}
However, as you see, I have no idea how to pass the condition as a parameter to the method.
I also don’t really know if this is how I create the iterator.
EDIT:
I’m not allowed to use any external libraries
Assuming that you are not allowed to use an external library like Guava, you could:
Filter<T>interface, that has one method, let’s call itboolean match(T obj).Filter<Element>to your iterator, that implements thematchmethod to test for the condition, for examplereturn "The name I'm looking for".equals(element.getName());.filter.match(element)thenresult.add(element).EDIT
Your new method would then be:
And you would call it this way:
the condition could be for example: