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;
}
你可以在方法内直接交换引用,但你不能通过函数调用交换,何况你那个交换函数还是错误的

解决方案 »

  1.   

    public class StringDemo {
       
        public static void main(String[] args) {
            int a[] = {1,3,5,7};
            int b[] = {2,4,6,8};
            change(a,b);
            System.out.println(a[0]+".."+b[0]);
        }  
        public static void change(int a[], int b[]){
            int temp[] =a;
                a = b;
                b = temp;
                System.out.println(a[0]+".."+b[0]);  
        } 
    }
    尼玛!我也是初学!想了半天!我知道问题所在了!但是改还没想好呢!问题就是调用方法的时候!change(a,b);和方法的参数列表change(int a[],int b[])   其实是 int a[]=a;b.....这就代表又新建了一个数组a[]
      

  2.   

    数组的交互 JAVA是提供方法的 system.arraycopy() 用这个方法就可以实现了
      

  3.   

    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好像是数组的复制吧。
      

  4.   

    看楼上说有System.arraycopy方法可以实现复制,我就用了下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如何解决交换数组而不用担心索引越界的问题?
      

  5.   

            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;
      

  6.   

            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;
      

  7.   

    temp保存的是要交换的引用,所以要交换两个数组的值只要让a 数组和b数组换个指向就可以了
      

  8.   

    使用临时数组,在用你的chang方法替换,参数是数组,而不是两个字符串。
      

  9.   

    lz想交换数组里的元素,change(a,b)中a,b都是数组类型而不是int,所以错了按照lz的思路可以这样写
    for(int i=0;i<a.lenght;i++){
    int temp=a[i];
    a[i]=b[i];
    b[i]=temp;
    }
      

  10.   

    java是值传递,地址值传递给参数,本身不会指向新地址