How do you reverse the order of an array in java?

Can u pls provide me the code that reverses the order of elements in an array in java? Thanks.

5 Answers

Relevance
  • Anonymous
    1 decade ago
    Favorite Answer

    public class ArrayHandle

    {

    public static Object[] reverse(Object[] arr)

    {

    List<Object> list = Arrays.asList(arr);

    Collections.reverse(list);

    return list.toArray();

    }

    }

    • Login to reply the answers
  • 1 decade ago

    If you really want to blow your teacher away here's an even faster way to reverse an array. This method is faster than everything that all these people posted.

    I'll write the general idea but I'll leave it to you to figure it out. Say you have an array of 10 items. You can loop through your array but instead of going through each element which will take you 10 iterations...just go through 5 elements and swap the first item with the last, the second item with the second last, third with the third to the last and so on and so forth until you get to the middle...then you're done!!!! You'll be able to reverse arrays faster then all the other students in your class.

    Yay!

    • Login to reply the answers
  • ?
    Lv 6
    1 decade ago

    Do you mean if the array was 1 thru 10 you want it 10 thru 1?

    Just do a for loop starting at the end of the array and put it in a temp array then back again.

    Say the array is this

    array {1,2,3,4,5,6,7,8,9,10};

    Make a temp array same size

    int j=o;

    for (int i=array.length-1; i >=0; i--)

    {

    temparray[ j++ ] = array[i];

    }

    for (i=0; i<array.length; i++)

    array[i]=temparray[i];

    • Login to reply the answers
  • 1 decade ago

    I haven't worked in java but should be the same as any other language. just play with the syntax a bit.

    temp=new array

    for (i=0 to length of array) {

    temp [i] = oldarray[length of array-i]

    }

    oldarray = temp

    • Login to reply the answers
  • How do you think about the answers? You can sign in to vote the answer.
  • 1 decade ago

    arrayObject.reverse()

    example,

    <script type="text/javascript">var arr = new Array(3)

    arr[0] = "Jani"

    arr[1] = "Hege"

    arr[2] = "Stale"document.write(arr + "<br />")

    document.write(arr.reverse())

    The output of the code above will be:

    Jani,Hege,Stale

    Stale,Hege,Jani

    • Login to reply the answers
Still have questions? Get your answers by asking now.