An Iterator which mutates and returns the same object. Bad practice?

Viewed 625

I'm writing GC friendly code to read and return to the user a series of byte[] messages. Internally I reuse the same ByteBuffer which means I'll repeatedly return the same byte[] instance most of the time.

I'm considering writing cautionary javadoc and exposing this to the user as a Iterator<byte[]>. AFAIK it won't violate the Iterator contract, but the user certainly could be surprised if they do Lists.newArrayList(myIterator) and get back a List populated with the same byte[] in each position!

The question: is it bad practice for a class that may mutate and return the same object to implement the Iterator interface?

  • If so, what is the best alternative? "Don't mutate/reuse your objects" is an easy answer. But it doesn't address the cases when reuse is very desirable.

  • If not, how do you justify violating the principle of least astonishment?

Two minor notes:

  • I'm using Guava's AbstractIterator so remove() isn't really of concern.

  • In my use case the user is me and the visibility of this class will be limited, but I've tried to ask this generally enough to apply more broadly.

Update: I'm accepting Louis' answer because it has 3x more votes than Keith's, but note that in my use case I'm planning to take the code that I left in a comment on Keith's answer to production.

3 Answers
Related