Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java Reverse ArrayList

This Java ArrayList Reverse example shows how to reverse elements of Java ArrayList.
  1. import java.util.ArrayList;
  2.  
  3. //Java Reverse ArrayList
  4.  
  5. /*
  6.  * This Java Reverse ArrayList shows how to reverse ArrayList without using new
  7.  * ArrayList object.
  8.  */
  9. public class JavaReverseArrayList {
  10.    
  11.     public static void main(String args[]){
  12.        
  13.         //create new ArrayList
  14.         ArrayList<String> alistNumbers = new ArrayList<String>();
  15.         alistNumbers.add("1");
  16.         alistNumbers.add("2");
  17.         alistNumbers.add("3");
  18.         alistNumbers.add("4");
  19.         alistNumbers.add("5");
  20.        
  21.         System.out.println("ArrayList before reverse: " + alistNumbers);
  22.        
  23.         String temp = null;
  24.         for(int start=0, end = alistNumbers.size()-1; start < end ; start++, end--){
  25.    
  26.             //swap the first and last element
  27.             temp = alistNumbers.get(start);
  28.             alistNumbers.set(start, alistNumbers.get(end));
  29.             alistNumbers.set(end, temp);
  30.            
  31.         }
  32.        
  33.         System.out.println("ArrayList after reverse: " + alistNumbers);
  34.     }
  35. }
  36.  
  37. /*
  38. Output of above given Java ArrayList Reverse example would be
  39. ArrayList before reverse: [1, 2, 3, 4, 5]
  40. ArrayList after reverse: [5, 4, 3, 2, 1]
  41. */
Your rating: None Average: 5 (1 vote)
Share this
Anonymous's picture

may i know why we need to

may i know why we need to swap first and last element? what is the logic behind this ?
Anonymous's picture

Well, If you need to reverse

Well, If you need to reverse elements of an ArrayList, i.e. first element should become last element, then last element will automatically become first. Consider arraylist with just 2 elements, what happen when you make first element last? Wouldn't it also make the last element first automatically?
mahesh19nov's picture

Why you're making it so

Why you're making it so complicated??? How about this??? Collections.reverse(alistNumbers);
Anonymous's picture

nice

nice
Anonymous's picture

Collections.reverse(alistNumb

Collections.reverse(alistNumbers); I guess this is more than enough!!!!!!!!
Anonymous's picture

Nice article, you have

Nice article, you have indeed covered the reversing arraylist in java in detail with code example. very handy for quick use.

Post new comment