搜尋此網誌

2012年3月17日 星期六

Java 變數指定


import java.util.ArrayList;

public class VariableAssignDemo {

public static void main(String[] args){
ArrayList a1 = new ArrayList();
a1.add(1);
/**
* Following case assigns object reference to a new variable
*/
ArrayList a2 =a1;
a2.add(2);
System.out.println(a1.toString());
System.out.println(a2.toString());

System.out.println("-------------------");

/**
* Following is a deep copy , all elements are included..
* If you want to keep original object , but do some changes on it.
* A deep copy is a solution.
*/
ArrayList a4 =new ArrayList();
for(int i = 0 ;i < a1.size() ;i++){
a4.add(a1.get(i));
}
a1.remove(0);
System.out.println(a1.toString());
System.out.println(a4.toString());

}
}

沒有留言:

張貼留言