Based on a question, the user wanted to access 99999th line of a 100000 lines file without having to iterate using an eachLineclosure 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?
As you can see from the code,
reverse()callsCollections.reversein Java to reverse the list.However the non-mutating code gives you another option. Using
listIterator()you can get an iterator withhasPreviousandpreviousto walk back through the list, so if you do:We can then do:
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:
Rather than all the reversing. Though obviously, this would need profiling to make sure I’m right…