Saturday, March 28, 2015

Reverse elements in Array

Reverse all elements in array, traditional way how we use to do is get the array and iterate through the for loop and use swap logic to move to temporary array and get the result.

But from > jdk 1.5 introduced reverse() in java.util.Collections which will reverse the order of the elements, all we have to do is to convert the array to arraylist by using Arrays.asList() and using collections.reverse() to reverse the order of the element.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author Uttesh Kumar T.H.
 */
public class ReverseArray {

    public static void main(String[] args) {
        Integer[] numbers = new Integer[]{1, 2, 3, 4, 5, 6};
        List numberlist = Arrays.asList(numbers);
        Collections.reverse(numberlist);
        for (int i = 0; i < numberlist.size(); i++) {
            System.out.println(numberlist.get(i));
        }

        // logical way of doing , its always good to understand the logic 
        int[] _numbers = {1, 2, 3, 4, 5, 6};
        for (int i = 0; i < _numbers.length / 2; i++) {
            int temp = _numbers[i]; // swap numbers 
            _numbers[i] = _numbers[_numbers.length - 1 - i];
            _numbers[_numbers.length - 1 - i] = temp;
        }
        System.out.println("reversed array : " + Arrays.toString(_numbers));
    }
}


0 comments:

Post a Comment