您的位置:首页 > 职场人生

swap - 普通程序员、文艺程序员、2B程序员

2011-11-09 15:11 337 查看
C、C++版:看到同学人人的发表日志,觉得有趣,然后就写下来。仅供娱乐。

普通程序员:

void swap (int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}


文艺程序员:

void swap (int &a, int &b)
{
a = a^b;
b = a^b;
a = a^b;
}


2B程序员:

void swap (int a, int b)
{
int temp = a;
a = b;
b = temp;
}


那么Java版的该如何呢?事实上,用Java去写一个int型的两个数,并不像C++中的那样简单,因为Java中不提供指针。想要像C++这样文艺起来并不容易。

下面是用Java实现的代码,估计能算个普通程序员吧,2B程序员就很容易弄了,文艺的就不知道怎样了(那就要靠大家的想法了):

public class Swap {

/**
* @param args
*/
@SuppressWarnings("unchecked")
static public void swap(Wrapper x, Wrapper y){
Wrapper z = new Wrapper(x.getA());
x.setA(y.getA());
y.setA(z.getA());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Wrapper<Integer> wA = new Wrapper<Integer>(1);
Wrapper<Integer> wB = new Wrapper<Integer>(2);
System.out.println("wA = " + wA.getA() + " wB = " + wB.getA());
swap(wA, wB);
System.out.println("wA = " + wA.getA() + " wB = " + wB.getA());
Wrapper<String> w1 = new Wrapper<String>("123");
Wrapper<String> w2 = new Wrapper<String>("456");
System.out.println("w1 = " + w1.getA() + " w2 = " + w2.getA());
swap(w1, w2);
System.out.println("w1 = " + w1.getA() + " w2 = " + w2.getA());
}
}
class Wrapper<T> {
private T a;
public Wrapper(T a){
this.a = a;
}
public T getA() {
return a;
}
public void setA(T a) {
this.a = a;
}
}


PS:顺带说一下,Java中的AtomicReference类也可以实现交换,和我上面的原理一样。之所以自己写一个Wrapper类,是为了大家看的简单点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: