我试图在Java中反转一个int数组。
此方法不反转数组。
for(int i = 0; i < validData.length; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
有什么问题吗?
我试图在Java中反转一个int数组。
此方法不反转数组。
for(int i = 0; i < validData.length; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
有什么问题吗?
当前回答
对非基本类型数组使用泛型的实现。
//Reverse and get new Array -preferred
public static final <T> T[] reverse(final T[] array) {
final int len = array.length;
final T[] reverse = (T[]) Array.newInstance(array.getClass().getComponentType(), len);
for (int i = 0; i < len; i++) {
reverse[i] = array[len-(i+1)];
}
return reverse;
}
//Reverse existing array - don't have to return it
public static final <T> T[] reverseExisting(final T[] array) {
final int len = array.length;
for (int i = 0; i < len/2; i++) {
final T temp = array[i];
array[i] = array[len-(i+1)];
array[len-(i+1)] = temp;
}
return array;
}
其他回答
这里是一个简单的实现,反转数组的任何类型,加上全/部分支持。
import java.util.logging.Logger;
public final class ArrayReverser {
private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());
private ArrayReverser () {
}
public static <T> void reverse(T[] seed) {
reverse(seed, 0, seed.length);
}
public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
if (seed == null || seed.length == 0) {
LOGGER.warning("Nothing to rotate");
}
int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
int end = Math.min(seed.length, endIndexExclusive) - 1;
while (start < end) {
swap(seed, start, end);
start++;
end--;
}
}
private static <T> void swap(T[] seed, int start, int end) {
T temp = seed[start];
seed[start] = seed[end];
seed[end] = temp;
}
}
下面是相应的单元测试
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
public class ArrayReverserTest {
private Integer[] seed;
@Before
public void doBeforeEachTestCase() {
this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}
@Test
public void wholeArrayReverse() {
ArrayReverser.<Integer>reverse(seed);
assertThat(seed[0], is(8));
}
@Test
public void partialArrayReverse() {
ArrayReverser.<Integer>reverse(seed, 1, 5);
assertThat(seed[1], is(5));
}
}
在Java 8的情况下,我们还可以使用IntStream来反转整数数组:
int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
.toArray(); //Output: [5, 4, 3, 2, 1]
public static void main (String args[]){
//create array
String[] stuff ={"eggs","lasers","hats","pie","apples"};
//print out array
for(String x :stuff)
System.out.printf("%s ", x);
System.out.println();
//print out array in reverse order
for(int i=stuff.length-1; i >= 0; i--)
System.out.printf("%s ",stuff[i]);
}
我认为如果你声明显式变量来跟踪你在每次循环迭代中交换的下标,那么遵循算法的逻辑会更容易一些。
public static void reverse(int[] data) {
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
我还认为在while循环中执行这个操作更具可读性。
public static void reverse(int[] data) {
int left = 0;
int right = data.length - 1;
while( left < right ) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// move the left and right index pointers in toward the center
left++;
right--;
}
}
简单的方法:
for(int i=queue.length-1;i>=0;i--){
System.out.print(queue[i] + " ");
}