Home » Java programs » Java ArrayList programs

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



In this program, we are going to create an ArrayList, add elements in the ArrayList and print elements in reverse order.
Submitted by IncludeHelp, on October 19, 2017

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.



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





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.