Reputation: 101
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;
}
Upvotes: 4
Views: 10124
Reputation: 137442
The problem with your solution is that Java is a pass-by-value language. So any change to list1
and list2
variables will not have an effect outside the method, but if this is not in a method, then it's ok.
Two more things:
list2 = tmpList;
, not list2 = list1;
.List<Integer>
.Upvotes: 4
Reputation: 1
You can use the swap method from Collections:
Collections.swap(Integer, list1, list2);
Upvotes: -3
Reputation: 114847
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:
public static void swapList(List<Integer> list1, List<Integer> list2){
List<Integer> tmpList = new ArrayList<Integer>(list1);
list1.clear();
list1.addAll(list2);
list2.clear();
list2.addAll(tmpList);
}
Some additional thoughts:
List<Integer> list1 = getList1Magic();
List<Integer> list2 = getList2Magic();
if (isSwapReferences()) {
// this does not affect the actual lists
List<Integer> temp = list2;
list2 = list1;
list1 = temp;
} else if (isSwapListContent()) {
// this modifies the lists
swapList(list1, list2); // method from above
}
The swap strategy depends on your requirements. First block has a local effect, second block a global one.
Upvotes: 14
Reputation: 8598
Minor correction in your approach:
ArrayList<Integer> tmpList = list1;
list1 = list2;
list2 = tmpList;
But you can not do this in a method the way you are doing.
Upvotes: 0
Reputation: 328923
You can't do it in a function because of Java is pass by value only. And you can't create a List of int, you can create a List of Integer.
You can try this to verify that it does not work:
public static void main(String... args) throws Exception {
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);
System.out.println(list1); //prints 1, 2, 3
swapList(list1, list2);
System.out.println(list1); //prints 1, 2, 3
}
public static void swapList(List<Integer> list1, List<Integer> list2){
List<Integer> tmpList = list1;
list1 = list2;
list2 = tmpList;
}
Upvotes: 2