2013年8月1日星期四

Java, swap FAQ

 
  

directly on the code ......

  
   
public class Swap { 

public static void main(String[] args) {
int a[] = new int[]{1,2};
System.out.println(a[
0] + " "+a[1]);
swap(a,
0,1);
System.out.println(a[
0] + " "+a[1]);

}
private static void swap(int[] a, int i, int j) {

int temp = a[i];
a[i]
= a[j];
a[j]
= temp;
}
}
  
 
 
  

method call (call by) is a standard computer scientific terms , the method call according to the parameters passed value of the case is divided into call (call by reference) , and reference calls ( call by value ). There are many rivers and lakes on the definition of these two calls , the most common argument is passed value is a value call delivery address is referenced calls. This is actually very appropriate , that these claims are easy to make we associate a Java object parameter passing is call by reference in fact , Java's object parameter passing value is still called. In the main output or the original 2,3 years , regardless of reference type is passed also is the object instance.

  
   
public class Swap1 
{
public static void main(String[] args)
{
Integer a
=new Integer(2);
Integer b
=new Integer(3);
TestSwap ts
=new TestSwap(a,b);
System.out.println(
"before swap:");
ts.outPut();
ts.dataSwap1(a,b);
System.out.println(
"after swap:");
ts.outPut();
}
}

class TestSwap
{
Integer a
=null;
Integer b
=null;

public TestSwap(Integer a,Integer b)
{
this.a=a;
this.b=b;
}
/*这样不可交换,交换的只是拷贝过来的引用,而
* 输出还是成员变量(输出用的是类内的方法)
* 重要的是,形参和实参所占的内存地址并不一样,
* 形参中的内容只是实参中存储的对象引用的一份拷贝。
*
*/
protected void dataSwap0(Integer a,Integer b)
{
Integer temp
=a;
a
=b;
b
=temp;
}
protected void dataSwap(Integer a,Integer b)
{
this.a = b;
this.b = a;
}
//这样也可以,不过需要类内的输出,就是说输出TestSwap的成员变量
protected void dataSwap1(Integer a,Integer b)
{
Integer temp
=this.a;
this.a=this.b;
this.b=temp;
}
protected void outPut()
{
System.out.println(
"a="+a+" b="+b);
}
}
  
 

1 条评论: