0

What is the most computationally efficient way to retrieve the last item in Apache circularfifobuffer? Last as in the latest to be added.

The only way I can see is to cycle through the whole buffer with .remove() or .iterator.next(). (The latter in conjunction with .size.) Is there a more efficient way? And with .iterator, will the order in which items are entered the buffer be preserved? For example, suppose I am interested in the 2nd latest item in a buffer with 10 items. Will calling .iterator.next() 9 times reliably accomplish the task?

I am new to Java. Please bear with me on what is probably an obvious question to others. Thank you.

Argyll
  • 8,591
  • 4
  • 25
  • 46
  • If you need this, why don't you use another data-structure? – Thilo Jul 20 '19 at 01:32
  • It's from a package which in turns uses an API. Two links downstream, I don't really have control over what gets used. As well, the API source code uses it for all its local caches. The cache for error listener makes most sense by making access to latest item convenient. But the cache for returned data from queries makes most sense by making access to the earliest item convenient. So they probably made a compromise somewhere. – Argyll Jul 20 '19 at 01:35
  • But yes, best way looks to be to get the `iterator()` and loop over it until `next()` no longer returns anything. (you need to get the iterator just once, not a fresh one every time, and this will not be thread-safe). – Thilo Jul 20 '19 at 01:36
  • I see. That's why I couldn't iterate through. I didn't know `iterator()` creates a new object every time. Why is that? (I could ask in a different question if you prefer.) – Argyll Jul 20 '19 at 01:41
  • `iterator()` gives you a new Iterator to capture the state of a single iteration (how often you called `next()` on it). This way the collection itself does not need to store this information internally (and you can do multiple iterations at once, all independent from each other). – Thilo Jul 20 '19 at 01:45
  • I see. Thank you for clarifying. – Argyll Jul 20 '19 at 01:47

0 Answers0