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();
Author by
user401183
Updated on May 05, 2021Comments
-
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 over 13 yearsYikes, thanks Ted. Looks like I have some java.util.* reading to do.
-
Ted Hopp almost 6 yearsAn improvement would be to create
tempElements
with an initial capacity at least equal to the size ofmElements
. That would avoid internal memory reallocations as elements are added in the second line. -
Ted Hopp almost 6 yearsAn improvement would be to create
newList
with an initial capacity at least equal to the size ofoldList
. That would avoid internal memory reallocations as elements are added in the loop. -
DarkCygnus almost 6 years@TedHopp thanks for the suggestion, will see to incorporate it to the answer :)