Here I will discuss about reversing elements in a List. The method used here works for all implementations of the java.util.List which include ArrayList, LinkedList and Vector classes. There is no logic that we need to write to reverse the elements. The method reverse(List) has done everything for us and we are just a method call away from it. Simple is that. This method is present in the java.util.Collections class and is available as static which means that it can be accessed without the need of creating an object. The order of the elements in the list is reversed. Here is a tiny example that illustrates this.
ReverseList.java
import java.util.*;
class ReverseList {
public static void main(String args[]) {
// Create an ArrayList containing String type elements
ArrayList < String > aList = new ArrayList < String > ();
// Add elements to the ArrayList aList
aList.add("Gowtham");
aList.add("Gutha's");
aList.add("java");
aList.add("-");
aList.add("demos");
aList.add(".");
aList.add("blogspot");
aList.add(".");
aList.add("com");
// Store the size of aList
// This avoids repeated calling of method in loops
int size = aList.size();
// Print elements before reversing
System.out.println("\nElements before reversing");
System.out.println("--------------------");
for (int i = 0; i < size; i++) {
System.out.println(aList.get(i));
}
// Reverse the elements in ArrayList
Collections.reverse(aList);
// Print the reversed elements
System.out.println("\nElements in reversed order");
System.out.println("--------------------");
for (int i = 0; i < size; i++) {
System.out.println(aList.get(i));
}
}
}
Output of the program
Elements before reversing
--------------------
Gowtham
Gutha's
java
-
demos
.
blogspot
.
com
Elements in reversed order
--------------------
com
.
blogspot
.
demos
-
java
Gutha's
Gowtham
Explaining the program
There is nothing in fact to explain in the program except the method which does it all. The java.util.Collections.sort(List l)
method takes in a java.util.List
object (i.e. object of any of it’s implementing classes) and sorts it. In a similar way you can do it for LinkedList
and Vector
also. Just Replace All ArrayList with LinkedList (for LinkedList) and with Vector
(for Vector), Stack
. That’s it.
Also see my post on sorting elements in a ArrayList, LinkedList and Vector
No comments:
Post a Comment