Below is a Java program to reverse the elements in an ArrayList of integers:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class ReverseArrayList {
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbersList = new ArrayList<>();
numbersList.add(5);numbersList.add(50);numbersList.add(15);numbersList.add(25); numbersList.add(5); // Reverse the elements in the ArrayList
Collections.reverse(numbersList);
// Print the ArrayList after reversing
System.out.println("ArrayList after reversing: " + numbersList);
}
}
Example usage:
ArrayList after reversing: [5,25,15,50,5]
Explanation:
- We start by creating an ArrayList of integers called numbersList.
- The user is prompted to input integers to add to the list, and the input loop continues until the user enters -1.
- After adding elements to the ArrayList, we use the Collections.reverse() method to reverse the elements in the list.
- The reverse() method modifies the original ArrayList in place and reverses the order of elements.
- Finally, we print the ArrayList after reversing the elements.
The Collections.reverse() method provides a convenient way to reverse the elements in an ArrayList without requiring a custom implementation using loops. It efficiently reverses the elements in linear time.
0 Comments