Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Simplest Way to Reverse an ArrayList?

What is the simplest way to reverse this ArrayList?

ArrayList<Integer> aList = new ArrayList<>();  //Add elements to ArrayList object aList.add("1"); aList.add("2"); aList.add("3"); aList.add("4"); aList.add("5");  while (aList.listIterator().hasPrevious())   Log.d("reverse", "" + aList.listIterator().previous()); 
like image 420
Ishu Avatar asked May 26 '12 13:05

Ishu


People also ask

How do you reverse an ArrayList?

An arraylist is created that takes only Employee(user defined) Objects. These objects are added to the arraylist using add() method. The arraylist is reversed using In-built reverse() method of Collections class. The printElements() static method is used only to avoid writing one more class in the program.

How do you reverse an ArrayList backwards in Java?

Use ListIterator to traverse an ArrayList in the reverse direction in Java. A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in the List Collection. So the ListIterator is only valid for classes such as LinkedList, ArrayList etc.


2 Answers

Collections.reverse(aList); 

Example (Reference):

ArrayList aList = new ArrayList(); //Add elements to ArrayList object aList.add("1"); aList.add("2"); aList.add("3"); aList.add("4"); aList.add("5"); Collections.reverse(aList); System.out.println("After Reverse Order, ArrayList Contains : " + aList); 
like image 65
Shankar Agarwal Avatar answered Oct 05 '22 23:10

Shankar Agarwal


Not the simplest way but if you're a fan of recursion you might be interested in the following method to reverse an ArrayList:

public ArrayList<Object> reverse(ArrayList<Object> list) {     if(list.size() > 1) {                            Object value = list.remove(0);         reverse(list);         list.add(value);     }     return list; } 

Or non-recursively:

public ArrayList<Object> reverse(ArrayList<Object> list) {     for(int i = 0, j = list.size() - 1; i < j; i++) {         list.add(i, list.remove(j));     }     return list; } 
like image 20
todd Avatar answered Oct 06 '22 01:10

todd