105. Reversing an array

There are several solutions to this problem. Some of them mutate the initial array, while others just return a new array. 

Let's assume the following array of integers:

int[] integers = {-1, 2, 3, 1, 4, 5, 3, 2, 22};

Let's start with a simple implementation that swaps the first element of the array with the last element, the second element with the penultimate element, and so on:

public static void reverse(int[] arr) {

for (int leftHead = 0, rightHead = arr.length - 1;
leftHead < rightHead; leftHead++, rightHead--) {

int elem = arr[leftHead];
arr[leftHead] = arr[rightHead];
arr[rightHead] = elem;
}
}

The preceding solution mutates the given array and this is not always the desired behavior. Of course, we can modify it to return a new array, or we can rely on Java 8 functional style as follows:

// 22, 2, 3, 5, 4, 1, 3, 2, -1
int[] reversed = IntStream.rangeClosed(1, integers.length)
.map(i -> integers[integers.length - i]).toArray();

Now, let's reverse an array of objects. For this, let's consider the Melon class:

public class Melon {

private final String type;
private final int weight;

// constructor, getters, equals(), hashCode() omitted for brevity
}

Also, let's consider an array of Melon:

Melon[] melons = {
new Melon("Crenshaw", 2000),
new Melon("Gac", 1200),
new Melon("Bitter", 2200)
};

The first solution entails using generics to shape the implementation that swaps the first element of the array with the last element, the second element with the second last element, and so on:

public static <T> void reverse(T[] arr) {

for (int leftHead = 0, rightHead = arr.length - 1;
leftHead < rightHead; leftHead++, rightHead--) {

T elem = arr[leftHead];
arr[leftHead] = arr[rightHead];
arr[rightHead] = elem;
}
}

Since our array contains objects, we can rely on Collections.reverse() as well. We just need to convert the array to a List via the Arrays.asList() method:

// Bitter(2200g), Gac(1200g), Crenshaw(2000g)
Collections.reverse(Arrays.asList(melons));

The preceding two solutions mutate the elements of the array. Java 8 functional style can help us to avoid this mutation:

// Bitter(2200g), Gac(1200g), Crenshaw(2000g)
Melon[] reversed = IntStream.rangeClosed(1, melons.length)
.mapToObj(i -> melons[melons.length - i])
.toArray(Melon[]:new);
For third-party library support, please consider Apache Common Lang (ArrayUtils.reverse()) and Guava's Lists class.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.204.0