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());
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.
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.
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);
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With