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

后端 未结 3 962
无人及你
无人及你 2020-12-19 02:54

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 re

3条回答
  •  别那么骄傲
    2020-12-19 03:23

    EnumMap did essentially exactly this in its entrySet() iterator, which causes confusing, crazy, depressing bugs to this day.

    If I were you, I just wouldn't use an Iterator -- I'd write a different API (possibly quite dissimilar from Iterator, even) and implement that. For example, you might write a new API that takes as input the ByteBuffer to write the message into, so users of the API could control whether or not the buffer gets reused. That seems reasonably intuitive (the user can write code that obviously and cleanly reuses the ByteBuffer), without creating unnecessarily cluttered code.

提交回复
热议问题