package JC.RnD.Soft.TestBed.Reference;
public class Reference
{
class Pointer
{
Object ref = null;
public Pointer()
{
this((Object)null);
}
public Pointer(Object o)
{
ref = o;
}
public void setObj(Object o)
{
ref = o;
}
public Object getObj()
{
return ref;
}
}
public static void main(String[] args) throws Exception
{
new Reference().run(args);
System.in.read();
}
public void swap(Pointer a,Pointer b)
{
Object tmp = a.getObj();
a.setObj(b.getObj());
b.setObj(tmp);
}
public void run(String[] args)
{
Pointer pa = new Pointer(new Integer(10));
Pointer pb = new Pointer(new Integer(20));
System.out.println("Integer a is: "+pa.getObj()+" Integer b is: "+pb.getObj());
swap(pa,pb);
System.out.println("Integer a is: "+pa.getObj()+" Integer b is: "+pb.getObj());
}
}
结果:
Integer a is: 10 Integer b is: 20
Integer a is: 20 Integer b is: 10
对于基本类型,可以通过扩展Pointer类实现。例如,对于int,可以加入:
Pointer(int);
void setInt(int);
int getInt();
类中需要加一个成员用于判断类型。使用可以这样:
pIntA = new Pointer(10);
pIntB = new Pointer(20);
...
swap(pIntA,pIntB);
System.out.println(pIntA.getInt());
...
不过这个“Pointer”用起来太痛苦了。