Reversing elements with reverse()

Reversing elements with reverse()


To reverse the elements of a data structure, there comes a method reverse() from Collections class. The method reverses all the elements in the original data structure itself. That is, after this method call, the original order in the list itself changes.
Following is the method.

  • static void reverse(List list1): Existing order of the elements in the List list1 are reversed. Again reversing gets the original order.
Following program on Reversing elements with reverse() uses the above method.

Reversing elements with reverse()

ArrayList myList = new ArrayList();
myList.add(10);

An ArrayList object myList is created and added a few elements with add() method inherited from Collection interface.

Collections.reverse(myList);

myList object is passed to reverse() method. The reverse() method reverses all the elements.

Set mySet = new HashSet();
mySet.add(“rao”);

After reversing the List elements, let us go for reversing of Set elements. For this, mySet object of HashSet is created and added a few elements with add() method.

// Collections.reverse(mySet); // ERROR

The above reverse operation raises compilation error as the parameter for reverse() method should be an object of List. That is, the reverse() method reverses only List elements.

List yourList = new ArrayList();
yourList.addAll(mySet);
Collections.reverse(yourList);

To overcome this difficulty, set elements are converted into list elements. mySet elements are passed to yourList with addAll() method and then reversed (interoperability between set and list). Now yourList prints mySet elements in reverse order.

To Reverse LinkedList Elements

In the following program, linked list elements are reversed. The same earlier procedure is followed.

Reversing elements with reverse()

LinkedList myList = new LinkedList();
myList.add(“one”);
Collections.reverse(myList);

A LinkedList object myList is created and added a few string elements. To reverse the elements, the object is passed to reverse() method of Collections class.

Note: StringBuffer also includes reverse() method to reverse a string.

One thought on “Reversing elements with reverse()

Leave a Reply

Your email address will not be published. Required fields are marked *