3 回答
TA贡献1840条经验 获得超5个赞
到目前为止你试过的代码在哪里?!
反正
for (int i = 0; i < array.length; i += 2) {
if(i+1 >= array.length) {
break;
}
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
TA贡献1921条经验 获得超9个赞
int[] array ={111,77,88,44,32,11,13,25,44};
int[] output = new int[array.length];
for(int x = 0; x < array.length - 1; x += 2) {
output[x] = array[x + 1];
output[x+1] = array[x];
}
if(array.length % 2 != 0) {
output[output.length-1] = array[array.length-1];
}
您只需遍历数组,并用交换的值填充新数组。
TA贡献1825条经验 获得超6个赞
这应该可以解决问题!
public static final <T> void swap (T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
public static final <T> void swap (List<T> l, int i, int j) {
Collections.<T>swap(l, i, j);
}
private void test() {
String [] a = {"Hello", "Goodbye"};
swap(a, 0, 1);
System.out.println("a:"+Arrays.toString(a));
List<String> l = new ArrayList<String>(Arrays.asList(a));
swap(l, 0, 1);
System.out.println("l:"+l);
}
添加回答
举报