How do I reverse an int array in Java?

前端 未结 30 2400
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 07:18

I am trying to reverse an int array in Java.

This method does not reverse the array.

for(int i = 0; i < validData.length; i++)
{
    int temp =          


        
30条回答
  •  遇见更好的自我
    2020-11-21 08:09

    Here is what I've come up with:

    // solution 1 - boiler plated 
    Integer[] original = {100, 200, 300, 400};
    Integer[] reverse = new Integer[original.length];
    
    int lastIdx = original.length -1;
    int startIdx = 0;
    
    for (int endIdx = lastIdx; endIdx >= 0; endIdx--, startIdx++)
       reverse[startIdx] = original[endIdx];
    
    System.out.printf("reverse form: %s", Arrays.toString(reverse));
    
    // solution 2 - abstracted 
    // convert to list then use Collections static reverse()
    List l = Arrays.asList(original);
    Collections.reverse(l);
    System.out.printf("reverse form: %s", l);
    

提交回复
热议问题