android - reverse the order of an array

52,241

Solution 1

You can do this in two steps:

ArrayList<Element> tempElements = new ArrayList<Element>(mElements);
Collections.reverse(tempElements);

Solution 2

Kotlin

val reverseList: List<Int> = yourActualList.reversed();

Reference

Share:
52,241
user401183
Author by

user401183

Updated on May 05, 2021

Comments

  • user401183
    user401183 about 3 years

    I have an array of objects.

    Is it possible to make a new array that is a copy of this array, but in reverse order? I was looking for something like this.

    // my array
    ArrayList<Element> mElements = new ArrayList<Element>();
    // new array
    ArrayList<Element> tempElements = mElements;
    
    tempElements.reverse(); // something to reverse the order of the array
    
  • Matthew Willis
    Matthew Willis over 13 years
    Yikes, thanks Ted. Looks like I have some java.util.* reading to do.
  • Ted Hopp
    Ted Hopp almost 6 years
    An improvement would be to create tempElements with an initial capacity at least equal to the size of mElements. That would avoid internal memory reallocations as elements are added in the second line.
  • Ted Hopp
    Ted Hopp almost 6 years
    An improvement would be to create newList with an initial capacity at least equal to the size of oldList. That would avoid internal memory reallocations as elements are added in the loop.
  • DarkCygnus
    DarkCygnus almost 6 years
    @TedHopp thanks for the suggestion, will see to incorporate it to the answer :)