Reversing a list in Java today is not straightforward. That is why this article is written. Technically, a List in Java is an interface. An interface is a class with method signatures that do not have definitions. A class has to be implemented from this interface before objects of the implemented class can be instantiated. In the implemented class, the methods are defined.
There is a class, still called List, in Java. However, this class is meant for string elements for the list. A list does not only have to be made up of strings. A list can consist of all floats, all doubles, all integers, etc. Each of these types, would need to be reversed, depending on the problem at hand. So this class is not mentioned any further in this article for the string List. Reversing a list in this article refers to the List interface made into a class and an object.
There are Java predefined list classes implemented from the List interface. These list classes are: AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, and the Vector.
Most of these list classes are in the java.util.* package.
Class Collections
The Collections class is also in the java.util.* package. The Collections class has a static reverse() method that returns void. Static-method means that the Collections class does not have to be instantiated before the reverse method is used. This method will take any of the previous list objects as an argument and reverse it.
Some expressions can return a general-purpose list object. The Collections reverse method will also reverse this list object when given as an argument.
The syntax for the Collections reverse() method is:
Reversing Manually
A list object in Java can also be reversed manually. Two of these manual methods are also explained in this article.
Reversing Using the Collections Reverse Method
Reversing a Predefined list
The following program reverses an ArrayList of alphabets:
public class TheClass {
public static void main(String[] args) {
ArrayList<Character> al = new ArrayList<Character>();
al.add('V'); al.add('W'); al.add('X'); al.add('Y'); al.add('Z');
Collections.reverse(al);
System.out.println(al);
}
}
The output is:
for an input of,
Note the way the Collections class and its reverse() method have been used.
Reversing a General Purpose Returned List
Assume that arr is an array of characters. The class, Arrays, in the java.util.* package, has the static method, asList(), which would take arr as an argument and return a fixed-size general-purpose list with the same characters. The static reverse method of the Collections class would still reverse this list. The following program illustrates this:
The output is:
Reversing a List Manually in Java
One way an array can be reversed is by swapping the elements. The last element is swapped with the first; the last-but-one is swapped with the second; the third to the last is swapped with the third; and so on. Two indexes, i and j, are needed for this process. The index i is from the beginning, and j is from the end. In the process, swapping caries on while i is less than j. All the elements are interchanged if the list has an even number size. If the list has an odd number size, then the middle element remains at its position. This way of reversing should be used with fixed-size lists and arrays.
The other way of manually reversing can be illustrated as follows:
Here’s the list to be reversed:
The last element, Z, is removed and inserted into the first position for the list to become:
The new last element is removed and inserted into the second position for the list to become:
The new last element is removed and inserted into the third position for the list to become:
The new last element is removed and inserted into the fourth position for the list to become:
Note that the size of the list never changed for each result. In this case, if j were the index of the last element, then the value of j would not change in the process. While the value of index i, from the beginning, would change from 0 to 3. So, i is incremented until it is just below j by one unit. This way of reversing is the remove-and-insert way.
This way cannot be used with the fixed-size list because an element cannot be removed with the fixed-size list.
Reversing by Swapping
The principal method to use here is the set() method of the list interface, whose complete syntax is:
The first argument for this method is the index of a particular element in the list. The second argument is the element to replace the element at the index position. The following program does swapping for a fixed-size list.
public class TheClass {
public static void main(String[] args) {
Character[] arr = new Character[] {'V', 'W', 'X', 'Y', 'Z'};
List<Character> lst = Arrays.asList(arr);
int j = lst.size() - 1;
for (int i=0; i<j; i++) {
char temp = lst.get(j);
lst.set(j, lst.get(i));
lst.set(i, temp);
j--;
}
System.out.println(lst);
}
}
The output is:
The swapping uses the classical code for swapping two values. In this case, the code is:
lst.set(j, lst.get(i));
lst.set(i, temp);
In the initialization statement, it is possible to initialize j in the for-loop. It is also possible to decrement j in the next-iteration statement of the for-loop. Two expressions, in this case, are separated by a comma. The previous for-loop is re-coded as follows:
public class TheClass {
public static void main(String[] args) {
Character[] arr = new Character[] {'V', 'W', 'X', 'Y', 'Z'};
List<Character> lst = Arrays.asList(arr);
for (int i=0, j = lst.size() - 1; i<j; i++, j--) {
char temp = lst.get(j);
lst.set(j, lst.get(i));
lst.set(i, temp);
}
System.out.println(lst);
}
}
Here, a one-for loop is handling two variables. The output is the same, as shown below:
Reversing by Remove-and-Insert
The remove-and-insert way cannot work with the returned fixed-size list. However, it can work with the predefined list classes. This way uses the list’s add() method, whose syntax is:
The “add” here means insert. That is: insert the element E at the index specified. After insertion, all the elements on the right are shifted one place.
It also uses the remove() method, whose syntax is:
This means: removing the element at the specified index and returning it. The following program does remove-and-insert (for reversing):
public class TheClass {
public static void main(String[] args) {
ArrayList<Character> al = new ArrayList<Character>();
al.add('V'); al.add('W'); al.add('X'); al.add('Y'); al.add('Z');
int j = al.size() - 1;
for (int i=0; i<j; i++) {
char temp = al.remove(j);
al.add(i, temp);
}
System.out.println(al);
}
}
The output is:
As expected and for this program, the value of j does not change from a general point of view.
It is possible to initialize j in the initialization statement in the for-loop. Two expressions, in this case, are separated by a comma. The previous for-loop is re-coded as follows:
public class TheClass {
public static void main(String[] args) {
ArrayList<Character> al = new ArrayList<Character>();
al.add('V'); al.add('W'); al.add('X'); al.add('Y'); al.add('Z');
for (int i=0, j = al.size() - 1; i<j; i++) {
al.add(i, al.remove(j));
}
System.out.println(al);
}
}
The output is:
As expected.
Conclusion
This article explained a list could be reversed by using the static reverse() method of the Collections class, where the list object becomes the method’s argument. Plus, a list can also be reversed manually by swapping elements or by using the remove-and-insert. We hope you found this article helpful. Check the other Linux Hint articles for more tips and tutorials.