class SwapClass {
public void swap(StringBuffer x,StringBuffer y){
x.append(y);
y=x;
}
public void swap(String x,String y){
String temp = x;
x = y;
y = temp;
}
public void swap(String[] arr,int x,int y){
String temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public void change(String x){
x ="franlk";
}
public void add(ArrayList al){
al.add("wang");
}
}
public class test {
/**
* @param args
*/
public static void main(String[] args) {
SwapClass obj = new SwapClass();
StringBuffer a = new StringBuffer("A");
StringBuffer b = new StringBuffer("B");
String[] arr ={"1","2"};
ArrayList al = new ArrayList();
al.add("zhang");
obj.swap(a,b);
System.out.println(a+","+b);
System.out.println("---------------------------------");
obj.swap(arr[0],arr[1]);
System.out.println(arr[0]+":"+arr[1]);
System.out.println("---------------------------------");
obj.swap(arr,0,1);
System.out.println(arr[0]+":"+arr[1]);
System.out.println("---------------------------------");
obj.change(arr[0]);
System.out.println(arr[0]);
System.out.println("---------------------------------");
obj.add(al);
System.out.println("al length======"+al.size());
}
}
运行结果
AB,B
---------------------------------
1:2
---------------------------------
2:1
---------------------------------
2
---------------------------------
al length======2
方法中改变引用变量指向对象不会影响方法外引用变量;
方法中改变引用变量指向对象的值会影响方法外引用变量的值。