Java – an iterator that transforms and returns the same object Bad practice?
I wrote GC friendly code to read and return a series of byte [] messages to the user Internally, I reuse the same ByteBuffer, which means that I will repeatedly return the same byte [] instance most of the time
I'm considering writing a warning Javadoc and exposing it to users as iterator < byte [] > AFAIK doesn't violate the iterator contract, but users will be surprised if they do lists Newarraylist (myiterator) and get a list filled with the same byte [] in each position!
The question is: is it bad practice for classes that may mutate and return the same object to implement the iterator interface?
>If so, what is the best choice? "Don't mutate / reuse your object" is a simple answer However, when reuse is highly desirable, it does not solve this situation. > If not, how can you justify the violation of the principle of least atonism?
Two notes:
>I'm using guava's abstractiterator, so remove () doesn't really care. > In my use case, the user is me, and the visibility of this class will be limited, but I have tried to apply this problem widely
Update: I accept Lewis's answer because it has three times more votes than Keith, but please note that in my use case, I intend to take the code I left to Keith's production answer
Solution
Enummap is basically exactly like this in its entryset () iterator, which leads to confusing, crazy and frustrating errors
If I were you, I wouldn't use iterators - I'd write a different API (maybe even completely different from iterators) and implement it For example, you can write a new API to write messages to ByteBuffer as input, so the user of the API can control whether the buffer is reused This seems quite intuitive (users can write code that clearly and cleanly reuses ByteBuffer) without unnecessary clutter