Saturday 28 May 2016

How to reverse an ArrayList in place in Java - Example

You can reverse an ArrayList in place in Java by using the same algorithm we have used to reverse an array in place in Java. If you have already solved that problem then It's a no-brainer because ArrayList is nothing but a dynamic array, which can resize itself. All elements of an array are stored in the internal array itself. By the way, if you need to reverse an ArrayList then you should be using the Collections.reverse() method provided by Java Collection framework. It's generic method, so you can not only reverse an ArrayList but also Vector, LinkedList, CopyOnWriteArrayList, or any other List implementation. Though, worth noting is that this method internally uses a ListIterator for reversing the list, which might not be as efficient as our algorithm.
Read more »

1 comment: