62,610
社区成员
发帖
与我相关
我的任务
分享
public class StringDemo {
public static void change(int a, int b){
int temp = a;
a = b;
b = temp;
}
public static void main(String[] args) {
int[] a = {1,3,5,7};
int[] b = {2,4,6,8};
change(a, b);
}
}
int[] a = new int[]{1, 2, 3, 4};
int[] b = new int[]{5, 6, 7, 8, 9};
int[] temp = null;
temp = a;
a = b;
b = temp;
[/quote]
int[] a = new int[]{1, 2, 3, 4};
int[] b = new int[]{5, 6, 7, 8, 9};
int[] temp = null;
temp = a;
a = b;
b = temp;
import java.util.*;
public class SwapArray{
public static void main(String[] args){
int[] a={1,2,3,4};
int[] b={2,3,4,5};
swop(a,b);
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
}
public static void swop(int[] a,int[] b){
int[] temp=new int[a.length];
System.arraycopy(a,0,temp,0,a.length);
System.arraycopy(b,0,a,0,b.length);
System.arraycopy(temp,0,b,0,temp.length);
}
}
使用数组一定要注意数组存放元素的个数是固定的,所以交换的时候两个数组的长度要相同,不然运行会报错:java.lang.ArrayIndexOutOfBoundsException
如何解决交换数组而不用担心索引越界的问题?package com.csdn_20141520;
public class ArraycopyTest {
public static void main(String[] args) {
int[] a = {1,3,5,7};
int[] b = {2,4,6,8};
change(a, b);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
System.out.println();
}
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]+ " ");
}
}
public static void change(int[] a, int[] b){
int[] temp = new int[4];
for (int i = 0; i < a.length; i++) {
temp[i] = a[i];
a[i] = b[i];
b[i] = temp[i];
}
}
}
楼上说的System.arraycopy好像是数组的复制吧。 public static void main(String[] args) {
int[] a = {1,3,5,7};
int[] b = {2,4,6,8};
int[] temp = a;
a = b;
b = temp;
}
你可以在方法内直接交换引用,但你不能通过函数调用交换,何况你那个交换函数还是错误的。。。