Start New Discussion within our Software Development Community
public static void main(String [] args){
		ArrayList<String> list1 = new ArrayList<String>();
		ArrayList<String> list2 = method(list1);
	private static ArrayList<String> method(ArrayList<String> list) {
		ArrayList<String> result = list;
		return result;

Could anyone explain this code to me? why it gives me the same result in list1 & list2..

thank you,

The secret of understanding this is to remember that list1, list2, list, and result are references (llike pointers) to an Object of type ArrayList<String>. The only way an actual ArrayList<String> object can be created is with the new keyword (line 3). If you follow the code 1 step at a time you will discover that there is only one ArrayList is this program, and that all those variables are just copies of the variable list1, so they all refer to the same object.
It's not easy to grasp 1st time round. Grab a sheet of paper with boxes for the variables and fill in the boxes as you step through the code. Remember the variables are references (pointers) they are not ArrayLists.

This question has already been answered. Start a new discussion instead.