java 数据交换

来源:互联网 发布:日本古代吃什么知乎 编辑:程序博客网 时间:2024/05/16 07:26

摘要

今天写了闲着没事,写了一个排序算法,其中一个写了一个交换的函数,发现并不起作用,后来想起来初学的时候同样犯过此错误,故在此将解决方法写下。

错误的交换函数

    public static void swap(int a,int b){        //这里使用异或运算比加法效率高些        System.out.printf("a=%d,b=%d\n",a,b);        a = a ^ b;          b = a ^ b;          a = a ^ b;        System.out.printf("a=%d,b=%d\n",a,b);    }

由于java基本类型是传值引用
此函数中,外部数据将值传给形参,a、b的作用域限定在swap函数,函数调用后,实际在函数外需要改变位置的数据没有产生变化。

解决思路

1.将交换后的值赋给返回值

public static int[] swap(int a,int b){        System.out.printf("a=%d,b=%d\n",a,b);        a = a ^ b;          b = a ^ b;          a = a ^ b;        System.out.printf("a=%d,b=%d\n",a,b);        return new int[]{a,b};    }

2.直接将数组及其下标传入

public static void swap(int[] arr,int i,int j){        arr[i]=arr[i]^arr[j];        arr[j]=arr[i]^arr[j];        arr[i]=arr[i]^arr[j];    }

jdk中Collections.swap的实现与其类似

/**     * Swaps the elements at the specified positions in the specified list.     * (If the specified positions are equal, invoking this method leaves     * the list unchanged.)     *     * @param list The list in which to swap elements.     * @param i the index of one element to be swapped.     * @param j the index of the other element to be swapped.     * @throws IndexOutOfBoundsException if either <tt>i</tt> or <tt>j</tt>     *         is out of range (i &lt; 0 || i &gt;= list.size()     *         || j &lt; 0 || j &gt;= list.size()).     * @since 1.4     */    public static void swap(List<?> list, int i, int j) {        final List l = list;        l.set(i, l.set(j, l.get(i)));    }

3.定义包装类,使得交换时是引用传递

class SwapInteger{        private int value;        public SwapInteger(int i) {            this.setValue(i);        }        public int getValue() {            return value;        }        public void setValue(int value) {            this.value = value;        }    }    public static void swap(SwapInteger a,SwapInteger b){        a.setValue(a.getValue()^b.getValue());        b.setValue(a.getValue()^b.getValue());        a.setValue(a.getValue()^b.getValue());    }

测试:

public static void main(String[] args) {        SwapInteger a=new SwapInteger(3);        SwapInteger b=new SwapInteger(4);        swap(a, b);        System.out.printf("a=%d  b=%d\n", a.getValue(),b.getValue());    }

输出:

a=4  b=3

这里java自带的int包装类Integer无法实现

4.

将需要交换的值声明为全局变量,在swap函数中赋值。
可实现但是意义不大。

原创粉丝点击