标签:style blog class code java color
首先我们来看一下在c/c++中实现的swap函数
void swap ( int & a, int & b)
{
int Temp;
temp = a;
a = b;
b = temp;
}那么在java中是否还能这样呢,很显然java中没有地址引用符号了。
首先我们来看下c/c++和java的区别。
本质区别
C/C++中swap功能的本质:通过传递变量地址(指针或引用)来交换变量地址中的值。
在Java世界中函数或者叫方法的入参都是通过值拷贝的方式进行传递:
Public static void swap ( int [] Data, int a, int b) {
int t = Data [a];
data [a] = data [b];
data [b] = t;
}Class MyInteger {
Private int x; / / the x as the only data member
Public MyInteger ( int xIn) {x = xIn;} / / Constructor
Public int getValue () { return x;} / / get the value
Public void insertValue ( int xIn) {x = xIn;} / / change the value of the
}
Public Class Swapping {
/ / Swap: pass object references
static void swap (MyInteger rWrap, MyInteger sWrap) {
/ / Change the value of the process
int t = rWrap.getValue ();
rWrap.insertValue (sWrap.getValue ());
sWrap.insertValue (t);
}
Public static void main (String [] args) {
int a = 23 , b = 47 ;
System.out.println ( "Before. a:" + a + ", b:" + b);
MyInteger AWRAP = new MyInteger (a);
MyInteger bWrap = new MyInteger (b);
swap (aWrap, bWrap);
a = aWrap.getValue ();
b = bWrap.getValue ();
System.out.println ( "After. a:" + a + ", b:" + b);
}
}Public Class Swap2 {
Public static void main (String args []) {
Swap2 SW = new Swap2 ( 1 , 2 );
System.out.println ( "i is" + sw.i);
System.out.println ( "J is" + sw.j);
sw.swap ();
System.out.println ( "i is" + sw.i);
System.out.println ( "J is" + sw.j);
}
int i, J;
Public Swap2 ( int i, int J) {
this . i = i;
this . J = J;
}
Public void swap () {
int Temp;
temp = i;
i = j;
j = temp;
}
}
Public Class swap1 {
Public static void swap1 (Integer a, Integer b) {
Integer temp = a;
a = b;
b = temp;
}
Public static void main (String args []) {
Integer a, b;
a = new Integer ( 10 );
b = new Integer ( 20 );
Swap1.Swap1 (a, b);
System.out.println ( "a is" + a);
System.out.println ( "b is" + b);
}
}c/c++和java实现swap函数的不同处,布布扣,bubuko.com
标签:style blog class code java color
原文地址:http://blog.csdn.net/speedme/article/details/25109817