Q:

Java program to add elements in ArrayList and print them in reverse order

belongs to collection: Java ArrayList Programs

0

Here, we are creating an ArrayList, adding 5 elements (100, 200, 300, 400 and 500) and printing them in reverse order.

To print elements in reverse order, we are running a loop from N-1 (Here, N is the total number of elements in the ArrayList) to 0.

To get the total number of elements of ArrayList, we use arrList.size() method of “ArrayList” class, here arrList is an object of ArrayList class.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program

import java.util.ArrayList;
 
public class ExArrayList {
 
  public static void main(String[] args) {
    ////Creating object of ArrayList
    ArrayList arrList = new ArrayList();
   
    //adding data to the list
    arrList.add("100");
    arrList.add("200");
    arrList.add("300");
    arrList.add("400");
    arrList.add("500");
   
    System.out.println("Array List elements: ");
    //display array list elements in reverse order
    for(int iLoop=arrList.size()-1; iLoop >= 0; iLoop--)
      System.out.println(arrList.get(iLoop));
   
  }
}

Output

Array List elements: 
500
400
300
200
100

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to remove elements from specific inde... >>
<< Java program to add element at specific index in A...