There are two ArrayList e.g.list1 = {1,2,3} and list2 = {7,6,4,2} How to can swap these two list. So the result will be list1 = {7,6,4,2} and list2 = {1,2,3}
Can I implement like this:
public void swapList(ArrayList<Integer> list1, ArrayList<Integer> list2){
ArrayList<Integer> tmpList = list1;
list1 = list2;
list2 = tmpList;
}
No you can’t implement it like that. Same with arrays. Pass-reference-by-value problem, like the others explained already.
If you want the lists to swap their content, then you have to clear and copy:
Some additional thoughts:
The swap strategy depends on your requirements. First block has a local effect, second block a global one.