Home » Java programming language

How to reverse ArrayList in Java?

Reversing an ArrayList: Here, we are going to learn how to reverse an ArrayList (elements of an ArrayList) in Java programming language?
Submitted by Preeti Jain, on September 13, 2019

Reversing an ArrayList

To reverse elements of an ArrayList in Java, we use reverse() method of Collections class.

reverse() method

  • reverse() method is available in java.util package.
  • reverse() method is used to reverse the elements of any Collection but here we are talking about ArrayList.
  • reverse() method does not throw any exception at the time of reversing an ArrayList.
  • reverse() method is a static method, it is accessible with the class name too (i.e. If we try to access with the class object then also we will not get any error or exception).
  • This is not a final method, it is overridable in child class.

Syntax:

    public static void reverse(Collection c);

Parameter(s):

  • Collection c – represents the name of Collection for which reverse ArrayList is to be returned.

Return value:

The return type of this method is void, it returns nothing or does not return any value.

Java program to reverse an ArrayList

// Java program to demonstrate the example of 
// reversing an ArrayList by using reverse() 
// method of Collections class.

import java.util.*;

public class ReverseArrayList {
    public static void main(String[] args) {
        // ArrayList Declaration
        ArrayList al = new ArrayList();

        // By using add() method to add few elements in 
        //ArrayList

        al.add(10);
        al.add(20);
        al.add(30);
        al.add(40);
        al.add(50);

        // Display ArrayList 
        System.out.print("Display ArrayList : " + " ");
        System.out.println(al);

        // By using reverse() method of Collections class is 
        // to reverse an ArrayList 
        Collections.reverse(al);

        // Display Reverse ArrayList
        System.out.print("Display Reverse ArrayList : " + " ");
        System.out.println(al);
    }
}

Output

Display ArrayList :  [10, 20, 30, 40, 50]
Display Reverse ArrayList :  [50, 40, 30, 20, 10]






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




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 some rights reserved.