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 < 0 || i >= list.size() * || j < 0 || j >= 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函数中赋值。
可实现但是意义不大。
阅读全文
0 0
- java day02 交换数据
- java 数据交换
- java 数据交换
- dojo与java交换数据
- 【JAVA】数据交换,java方法参数
- hdoj2016(java)数据的交换输出(数组交换)
- Java数据类型与JSON的数据交换
- JSON与java各种数据的交换
- Java之数据的交换比较
- JAVA-UDP初步:数据交换示例
- Java编程中 交换数据的值
- java中交换两个数据的方法
- hdu2016数据的交换输出 java
- Java Exchanger(两线程交换数据)
- Java--位运算;两数据交换
- 数据交换文件DXF简单java解析
- java 线程间交换数据的Exchanger
- java核心技术卷 之对话框数据交换
- mysql/jdbc:设置useInformationSchema=true读取表注释信息(table_comment)
- Tensorflow学习:简单实现卷积神经网络(CNN)
- Angular基础(三) TypeScript
- Python中的__new__()方法的使用实例
- 服务器select与gevent
- java 数据交换
- JZOJ2017.08.14 B组
- Go语言学习笔记 --- reflection
- 蔡勒公式
- 交换变量的方法,不使用第3变量
- PAT题解——1020. Tree Traversals
- 用python写网络爬虫-英文翻译
- 5.判断语句与循环语句
- yii2表单get多次提交时一直在地址重复拼接参数