Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I swap two arraylist in JAVA?

Tags:

java

arraylist

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;
}
like image 326
Renjun Zou Avatar asked Dec 03 '22 04:12

Renjun Zou


2 Answers

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.

like image 84
Andreas Dolk Avatar answered Dec 09 '22 16:12

Andreas Dolk


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:

  1. You probably meant list2 = tmpList;, not list2 = list1;.
  2. You cannot use generic with primitives, should be List<Integer>.
like image 29
MByD Avatar answered Dec 09 '22 14:12

MByD