Reversing an ArrayList is part of a collection of standard algorithms.
Reversing an ArrayList
in-place can be accomplished using the same algorithm as reversing an array in-place.
Returning a new ArrayList
with the elements of the original list in reverse order is handled differently.
Return an ArrayList
in reverse order
Algorithm
Create a new empty ArrayList.
Loop through the entire original ArrayList.
Add each element of the original list to the beginning (index 0) of the new list.
Implementation in Java
public static ArrayList<String> getReversed(ArrayList<String> list)
{
ArrayList<String> reversed = new ArrayList<String>();
for(String str : list)
{
reversed.add(0, str);
}
return reversed;
}
Help & comments
Get help from AP CS Tutor Brandon Horn