Senthil Kumaran
Senthil Kumaran

Reputation: 56861

Implement an Iterable interface with a single item

I have this snippet, where I want to return a single instance board to test the solution. What's a good way to return a single item and exhaust the Iterator?

Placing it an final List and then emptying it an only option?

 public Iterable<Board> solution() {
        return new Iterable<Board>() {
            @Override
            public Iterator<Board> iterator() {
                return new Iterator<Board>() {
                    @Override
                    public boolean hasNext() {
                        return false; // change this
                    }

                    @Override
                    public Board next() {
                        return board;    // This does not work
                    }

                    @Override
                    public void remove() {

                    }
                };
            }
    };
}

Upvotes: 0

Views: 7615

Answers (2)

Senthil Kumaran
Senthil Kumaran

Reputation: 56861

The answer given by @nickb lead me to see how Singleton implements the iterator and I could come up with the following approach (for my learning /testing). For production code, I will prefer @nickb's answer.

public Iterable<Board> solution() {
    return new Iterable<Board>() {
        /**
         * Returns an iterator over a set of elements of type T.
         *
         * @return an Iterator.
         */
        @Override
        public Iterator<Board> iterator() {

            return new Iterator<Board>() {
                private boolean hasNext = true;
                @Override
                public boolean hasNext() {
                    return hasNext;
                }

                @Override
                public Board next() {
                    if (hasNext) {
                        hasNext = false;
                    }
                    return board;
                }
                @Override
                public void remove() {

                }
            };
        }
    };
}

Upvotes: 0

nickb
nickb

Reputation: 59699

I think you might be overthinking this just a bit, any Collection is an Iterable, so you could do something as simple as:

public Iterable<Board> solution() {
    return Collections.singleton(board);
}

Upvotes: 15

Related Questions