Is the reverse() method in groovy merely an abstraction of an iteration?
groovy, iteration, loops
Solution
As you can see from the code, `reverse()` calls `Collections.reverse` in Java to reverse the list.
However the non-mutating code gives you another option. Using `listIterator()` you can get an iterator with `hasPrevious` and `previous` to walk back through the list, so if you do:
// Our list
def a = [ 1, 2, 3, 4 ]
// Get a list iterator pointing at the end
def listIterator = a.listIterator( a.size() )
// Wrap the previous calls in another iterator
def iter = [ hasNext:{ listIterator.hasPrevious() },
next:{ listIterator.previous() } ] as Iterator
We can then do:
// Check the value of 1 element from the end of the list
assert iter[ 1 ] == 3
However, all of this is an ArrayList under the covers, so it's almost certainly quicker (and easier for the code to be read) if you just do:
assert a[ 2 ] == 3
Rather than all the reversing. Though obviously, this would need profiling to make sure I'm right...
Problem
Based on a question, the user wanted to access 99999th line of a 100000 lines file without having to iterate using an `eachLine`closure on the first 99998 lines. So, I had suggested that he use `file.readLines().reverse()[1]` to access the 99999th line of the file. This is logically appealing to a programmer. However, I was quite doubtful about the intricacy regarding the implementation of this method. Is the `reverse()` method a mere abstraction of the complete iteration on lines that is hidden from the programmer or is it really as intelligent as to be able to iterate over as less number of lines as possible to reach the required line?