Write a Java program to reverse elements in a array list


This code creates an ArrayList of String type named list_col and adds 7 elements to it. It then prints the ArrayList before and after reversing it using the Collections.reverse() method. Here is how the code works:

  • An ArrayList of String type list_col is created.
  • Seven string elements are added to the ArrayList using the add() method.
  • The ArrayList is printed using the println() method and the text "Before Reversing :".
  • The Collections.reverse() method is called with the ArrayList as the parameter to reverse the order of the elements in the ArrayList.
  • The ArrayList is printed again using the println() method and the text "After Reversing :".

Source Code

import java.util.*;
public class Reverse_ArrayList
{
	public static void main(String[] args)
	{
		List<String> list_col = new ArrayList<String>();
		list_col.add("Black");
		list_col.add("Orange");
		list_col.add("Pink");
		list_col.add("Blue");
		list_col.add("White");
		list_col.add("Yellow");	
		list_col.add("Purple");
		System.out.println("Before Reversing :" + list_col);  
		Collections.reverse(list_col);
		System.out.println("After Reversing :" + list_col); 
	}
}

Output

Before Reversing :[Black, Orange, Pink, Blue, White, Yellow, Purple]
After Reversing :[Purple, Yellow, White, Blue, Pink, Orange, Black]

Example Programs