Appendix D. Answers to Exercises
The solutions provided in this appendix are sample answers. Not every chapter had exercises at the end, but it is hoped that the ones provided will give you ample opportunity to put what you've learned into practice. We encourage you to experiment with each chapter's concepts.
Exercises
Create an iterator that only returns the value of every nth element, where n is any integer greater than zero.
Create a predicate that performs a Boolean AND (
&&) of two other predicates.Re-implement
PowerCalculatorusing recursion instead of iteration.Replace the use of arrays with iterators in the recursive directory tree printer.
Create an iterator that holds only a single value.
Create an empty iterator that is always done.
Exercise 1 Solution
package com.wrox.algorithms.iteration;
public class SkipIterator implements Iterator {
private final Iterator _iterator;
private final int _skip;
public SkipIterator(Iterator iterator, int skip) {
assert iterator != null : "iterator can't be null";
assert skip > 0 : "skip can't be < 1";
_iterator = iterator;
_skip = skip;
}
public void first() {
_iterator.first();skipForwards(); } public void last() { _iterator.last(); skipBackwards(); } public boolean isDone() { return _iterator.isDone(); } public void next() { _iterator.next(); skipForwards(); } public void previous() { _iterator.previous(); skipBackwards(); } public Object current() throws IteratorOutOfBoundsException { return _iterator.current(); } private ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access